display images dynamically in repeater tag - c#

I have multiple images which i want to display. the image count varies on input. I am able to see the broken images on the screen. In console the ERR_INVALID_URL is displayed. Please let me know where i am wrong.
Below is my aspx code
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image3" runat="server"
ImageUrl="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
</ItemTemplate>
</asp:Repeater>
cs code
foreach (DataRow row in dt.Rows)
{
Byte[] bytes = (Byte[])row["image"];
viewDataList.Add(new view_data { image = Convert.ToBase64String(bytes)});
}
Repeater1.DataSource = viewDataList;
Repeater1.DataBind();
I am fetching the images from database.Is this the correct way to do this.. Kindly suggest
Update..
I have changed the image tag to the below. Now there are 4 images that need to be displayed out of which i am able to see 1 image and the rest 3 are broken.. Kindly suggest
<img src="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />

Try in this way with your requirements. Let me know, if you have any issues once you completed with below methods.
Note: I tried with separate column name as Image ID.If you have it in your database it will be of more useful to proceed this. Otherwise, you pass the Image directly to the repeater and pass the same to the ImageHandler.ashx
HTML Page:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Image ID="Image3" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Height="150px" Width="150px"/>
</ItemTemplate>
CS Code:
On your click event:
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]",connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
ImageHandler.ashx
After Completion of above code we need to add HTTPHandler file to our project to retrieve images from database because we save our images in binary format getting the binary format of data from database it’s easy but displaying is very difficult that’s why we will use HTTPHandler to solve this problem.
Here HTTPHandler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance.
Right Click on your project add new HTTPHandler.ashx file and give name as ImageHandler.ashx and write the following code in pagerequest method like this
string strcon =ConfigurationManager.AppSettings["ConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID="+ imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this
<connectionStrings>
<add name="dbconnection" connectionString="DataSource=Yourservername;Integrated Security=true;InitialCatalog=Your databasename"/>
</connectionStrings>
Source: Retrieve Image from database

Changing the image tag to the below worked for me..
<img src="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />
Thanks for your response

There is no need to foreach to bind data in repeater you can directly specify DataTable to Your repeater control
DataTable dt=new DataTable();
dt=cmd.ExecuteNonQuery();
Repeater1.DataSource = dt;
Repeater1.DataBind();
you can place this line
<asp:Image ID="Image3" runat="server"
ImageUrl='<%#Bind("image")%>' />
instead of
<asp:Image ID="Image3" runat="server"
ImageUrl="data:image/jpg;base64,<%# ((view_data)Container.DataItem).image%>" />

Related

How to retrieve image from database(image stored is in binary form)

this is the place where i want to display the images
`<asp:Repeater ID="rptr" runat="server">
<ItemTemplate>
<asp:Image ID="img1" style="height:120px; width:120px" runat="server" />
</ItemTemplate>
</asp:Repeater>
`
this is the code i have used to retrieve images
string query = "select Image from tblImage where UserName='" + uname + "'";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(query, scon);
da.Fill(ds);
rptr.DataSource = ds;
rptr.DataBind();
now i want to set imageurl for the image control present within repeater control but the problem is that my image is present in binary form so i cant set the imageurl as ImageImageUrl='<%#Eval("Image") %>'("Image" is Column Name of the table where Image is stored in binary form). How can i convert the image into string format and set that into ImageUrl
HTML img element like so:
<asp:Image ID="image" style="height:120px; width:120px" runat="server"/>
And in code behind do this:
image.src = "data:image/png;base64," + Convert.ToBase64String(imageBytes);
Where imageBytes is a byte[] which you retrieve from database.
You are done. The image will be displayed.

Nesting Repeater Throws Casting Error

I currently have a parent repeater and two child repeaters on my page. I am wanting to dynamically pull data from our database and display them within the repeaters. I followed the Microsoft guide and a few SO questions on how to do this, and this is what I have arrived at:
<!-- start parent repeater -->
<asp:repeater id="parentRepeater" runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %>"><%# DataBinder.Eval(Container.DataItem,"EquipmentTypeName") %><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater1 -->
<asp:repeater id="Repeater1" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"MakeID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
<!-- start child repeater2 -->
<asp:repeater id="childRepeater2" datasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>' runat="server">
<itemtemplate>
<li><div id="et_<%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%>"><%# DataBinder.Eval(Container.DataItem, "[\"YearID\"]")%><label><input type="checkbox"></label></div><ul runat="server">
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater2 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end child repeater1 -->
</ul></li></itemtemplate>
</asp:repeater>
<!-- end parent repeater -->
And the code behind is as follows:
protected void Page_Load(object sender, EventArgs e)
{
//Create the connection and DataAdapter for the Authors table.
string Connection = WebConfigurationManager.ConnectionStrings["md_dbConnectionString"].ConnectionString;
SqlConnection cnn = new SqlConnection(Connection);
SqlDataAdapter cmd1 = new SqlDataAdapter("select * from EquipmentType", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "EquipmentType");
SqlDataAdapter cmd2 = new SqlDataAdapter("select * from Make", cnn);
cmd2.Fill(ds, "Make");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd3 = new SqlDataAdapter("select distinct MakeID, TypeID, YearID from Parts", cnn);
cmd3.Fill(ds, "Parts");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("myrelation",
ds.Tables["EquipmentType"].Columns["EquipmentTypeID"],
ds.Tables["Parts"].Columns["TypeID"]);
ds.Relations.Add("myrelation2",
ds.Tables["Make"].Columns["MakeID"],
ds.Tables["Parts"].Columns["MakeID"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds;
Page.DataBind();
//Close the connection.
cnn.Close();
}
If I load the page with only one child repeater, everything works fine, I get the correct data displaying, but when I add the second child repeater in, I get the following error message: Unable to cast object of type 'System.Data.DataRow' to type 'System.Data.DataRowView'. This fires on thedatasource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myrelation2") %>'` ASP line.
The tables that I am trying to pull from are structured this way:
EquipmentType
EquipmentTypeID | EquipmentTypeName
Make
MakeID | MakeName
Year
YearID
Parts
PartID | MakeID | YearID | TypeID
Each table references the Parts table.
More or less what I want the repeater to do is display all of the EquipmentTypes, then only display the make is we have a part for it in the database. Once the make is selected, then only display the year that we have parts for that make and equipmenttype in the database.
Did you try to cast it to DataRow:
<%# ((DataRow)Container.DataItem).GetChildRows("myrelation2") %>
For anyone else experiencing this issue. It could be that there is a missing tag at the top of the page. <%# Import Namespace="System.Data" %>

Using C# to get multiple results into GridView cell

Very new to writing code, please be gentle...
I have a database that keeps track of images that I post online, who was in the image, date taken, etc. I then have an ASPX page that based on the ID I pass in brings me back a gridview of the image, location online etc. This helps me keep track of how many places I may have used a single image.
Everything works great, but I get one row per image URL in my grid view. I want to have the image appear once on my page, then one of the cells list out the URLs.
Here is my C#:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["db2257conn"].ConnectionString;
String strQuery = "select mFirstName, mDOB, cURL, fID, fURL, cDate from vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN(mID1, mID2, mID3) and cactive = 1 order by cDate, fType, fName, cURL";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView2.DataSource = dt;
GridView2.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
}
Here is the ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="modelcontent2.aspx.cs" Inherits="modeldatabase.modelcontent2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" Font-Names="Arial" OnSelectedIndexChanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="fURL" DataTextField="furl" DataTextFormatString="<img src='{0}' width='200' border='0' />" Target="_blank" HeaderText="Image Link" Text="Image Link" />
<asp:BoundField DataField ="cDate" HeaderText ="Shoot Date" />
<asp:BoundField DataField ="mFirstName" HeaderText="Model First Name" />
<asp:BoundField DataField="mDOB" HeaderText="DOB" />
<asp:BoundField DataField="fID" HeaderText="File ID" />
<asp:HyperLinkField DataNavigateUrlFields="cURL" DataTextField="cURL" HeaderText ="URL" Target="_blank" Text="URL" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
And my rep is too new to post an image of the results, but suffice it to say I see multiple rows for the same image, one for each URL.
I'd like to see the image and other data as a single row, then in the URL column have all of the URLs that the image appears at.
Maybe not very performant but try a subselect
String strQuery = "select mFirstName, mDOB, (SELECT cURL + ',' FROM vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN (mID1, mID2, mID3)) , fID, fURL, cDate from vwAllModelContent where " + Context.Request.QueryString["mID"] + " IN(mID1, mID2, mID3) and cactive = 1 order by cDate, fType, fName, cURL LIMIT 1";
I'm not sure if it works, didn't use sql for a long time
Question: Why do you have three columns for IDs? (mID1, mID2, mID3)
What you are defining is called a "1 to many" relationship.
Gridview's are designed to show multiple rows tabular type data. If you want to display 1 image and multiple rows of associated data there are several ways of doing this.
Typically this would require 2 database calls:
one that returns the image source link
one that returns the rows of associated data.
Since the first call is really only providing an img src you don't really need a databound control for that, just obtain the string and drop it into an <asp:Image /> control or an <asp:ImageButton /> (if you prefer the image to be a link) and set the ImageUrl property
The second call is returning multiple rows of data, use your existing Gridview, you only need to remove the image reference.

Images not displaying, asp:repeater

Im trying to display name, description and a picture from my database with a repeater.
The Name and Description works as they should but the images won't show up. The images is located in a folder in my project and I'm trying to access them with a string that i have stored in the database "path" column.
oh, but if I look at the source code of the browser the src="" looks good, and i can even look at the pic in the browser if i paste the src to it..
Heres my code:
<head runat="server">
<title></title>
<style type="text/css">
.bilder {width:300;
height:200;
margin: 10px;
border: 1px solid black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater runat="server" ID="minRepeater">
<ItemTemplate>
<div class="wrapper">
<h1><%# DataBinder.Eval(Container.DataItem, "Name") %></h1>
<span id="desc"><%# DataBinder.Eval(Container.DataItem, "Description") %></span><br />
<img src="<%# DataBinder.Eval(Container.DataItem, "Path") %>" alt="test" class="bilder" />
<asp:Image ID="Image1" CssClass="bilder" ImageUrl='<%# DataBinder.Eval(Container.DataItem, "Path")%>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
and codebehind:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = connectionstring;
SqlCommand com = new SqlCommand();
com.CommandText = "SELECT * FROM Pictures";
com.Connection = con;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = com;
DataTable dt = new DataTable();
ad.Fill(dt);
Response.Write(dt.Rows.Count);
minRepeater.DataSource = dt;
minRepeater.DataBind();
}
(yes i know that my code isn't safe. at all.)
here's how it looks in a browser:
any ideas? :)
You may run it in Firebug or Chrome and see if the images are not found (404) and theirs path.
The error you're getting Not allowed to load local resource sounds like you are trying to load using a path on your local system. Trying using Server.MapPath with a relative path to the file, for example:
Server.MapPath("~/images/my-image.jpg");
Is your path like C:\\Images\etc...? If you are getting "Not allowed to load local resource", you should try your paths with relative paths.. if you dont have them in the WebSite you should make a copy of the image to the site and render that path. You are facing security problems.

How to retrieve DataTable value to <div> in ASP.NET

I am new to ASP.NET, I am making a search box in my application.
For example: if a user enters "abc" in the textbox, then the textbox will fetch data from the database which starts with "abc". I am passing this data to DataTable.
It works properly,
Here is my code snippet:
DataTable result = new DataTable();`
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
}
Now I want to retrieve all this data in my <div> tag. How should I retrieve and display?
Any help will be appreciated.
You should use a databound control like a ListView or GridView. I'd recommend creating a separate control to hold one row in the list and using the RowDataBound method to assign the row data. Example of using ListView's ItemDatabound event - http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx
On a side note your code is vulnerable to SQL Injection
You could probably better use a databound control, like the ListView (or the GridView) control. This way you can create nice layouts you want with the data in the datatable.
For instance, a ListView could be used:
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("ColumnFromDataTable")%>
</div>
</ItemTemplate>
</asp:ListView>
In your code behind you can then do:
lvwItems.DataSource = result;
lvwItems.DataBind();
Remark: code is just out of my head, could contain some errors

Categories

Resources