Monday, May 21, 2012

Grid View Data Bind with an Image field

Today I’m going to discuss how to bind data to Grid View component that has image field. ( using C#)
Let’s do it step by step.

Step 1 – Create the Grid View component.

I’m using only three columns(File Name, Status , ImageStatus) Following shows the Source view. This can be done by Design view easily.

<asp:GridView ID=”GridView1″ runat=”server”  Width=”500px” PageSize=”12″ >
<asp:BoundField HeaderText=”File Name”  DataField=”FileName”
 HeaderStyle-Width=”300px” ></asp:BoundField>
<asp:BoundField HeaderText=”Status DataField=”Status” > </asp:BoundField>
<asp:ImageField HeaderText=”ImageStatus”  DataImageUrlField=”ImageUrl”>   </asp:ImageField>

Step 2 — Get required data to data table
I’m not going to explain this step. I assume that GetTable() method do data retrieving part and store them to fileInfo DataTable. This DataTable contains FileName and Staus columns.

DataTable fileInfo = GetTable();

Step 3 – Create DataSet and Add new ImageUrl column.
This ImageUrl contains appropriate image for Status column.

 gridSet = new DataSet();
gridSet.Tables[0].Columns.Add(“ImageUrl”, typeof(String));

Step 4 – Add the Image URL to ImageUrl column
Assume that Status column have two values(R-Readable and U-Unreadable) . Now we are going to map the image suitable for status  of the file.

for (int i = 0; i < gridSet.Tables[0].Rows.Count; i++)
  switch (gridSet.Tables[0].Rows[i].Field<Char>(“Status”))
case ‘R’:
gridSet.Tables[0].Rows[i]["ImageUrl"] = “\\Server1\Files\Images\ readable.png”;
case ‘U’:
gridSet.Tables[0].Rows[i]["ImageUrl"] = “\\Server1\Files\Images\unreadable.png”;

Step 5 – Bind the Data to Grid View

this.GridView1.DataSource = gridSet.Tables[0];

That’s all. See the following grid view sample. Post your comments !


No comments:

Post a Comment