Home » ASP.Net, GridView Tips, Tech Corner

How to Bind Images from Database in a GridView

1 December 2009 No Comments Posted By:Vivek

Binding Images to a Gridview has been explained in this article. For this , first start a new application with ASP.NET and drop a GridView control onto the aspx page.Now add a new template Column to the GridView.In addition,if you want to display anything else, add bound fields or template fields according to your needs.In here, i have used a bound fied to display the image Id and the template field to display the Image.Now In the template field,add an Image control as the item template.For this just click on Edit Item Template and add an Image as Itemtemplate. Dont forget to uncheck the ‘AutoGenerateColumns’ checkbox.The complete code for the GridView is as follows.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="ProductID" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Now to display images. Here in the database,only the file names is there and hence if the images are in some directory, you have to somehow pre pend it with the filename.Here i am using the appsettings in web.config to provide the path of the images directory.

<appSettings>
<add key="IMG" value="http://your full path"/>
</appSettings>

Now to the C# code for populating the GridView. Here is the entire method i created for binding this GridView.

private void bindGrid()
{
string strconn= ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strconn);
con.Open();
string cmdText = "Select productId,Filename from Images"
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();

for (int i = 0; i < dt.Rows.Count; i++)
{
GridView1.Rows[i].Cells[0].Text = dt.Rows[i]["ProductId"].ToString();
GridView1.Rows[i].Cells[2].Text = dt.Rows[i]["Filename"].ToString();
Image PImage = (Image)GridView1.Rows[i].FindControl("Image1");
PImage.ImageUrl = ConfigurationManager.AppSettings["IMG"].ToString() + dt.Rows[i]["FileName"].ToString();
}
con.Close();
}

Though this method will be slow if you want to populate huge amount of data, it is quite effective. Now here in the first line, i am taking the connection string from the web.config.The next few steps are self explanatory as you can see.You may be wondering why i have binded the Grid and after that i am populating it again. That is because, when the for loop runs, if the GridView is not binded, the Index was out of range index error will be shown.
Now in the for loop, the first cell, which contains the bound field, text is set to the ImageId. The second line in the loop, we are finding the image control we had added before as the template field in the GridView.”Image1″ is the ID of the Image Control.Now all that is remaining is setting the ImageUrl property of the found image control. Before that we prepend the FileName with the directory path.

Hope this helps.As i said, this method may be slow if you have many images to be populated.

Related posts:

  1. Dropdownlist inside a Gridview
  2. Edit,Update,Cancel In a GridView
  3. Populating ASP.NET TreeView Control from DataBase
  4. ConfigurationManager Class and the use of web.config file
  5. FileUpload Control

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>