Load Image Dynamically in GridView

Manojjupally
Posted by Manojjupally under ASP.NET category on | Points: 40 | Views : 1136
Assuming there are flower1.bmp and flower2.bmp images in the Images folder of your project.

Data Table to bind the grid

public DataTable CreateDataTable()
{
DataTable dtUsers = new DataTable();

dtUsers.Columns.Add("Name",typeof(string));
dtUsers.Columns.Add("Dept", typeof(string));
dtUsers.Columns.Add("Sal", typeof(decimal));
dtUsers.Columns.Add("ImageName", typeof(string));

DataRow drUsers = dtUsers.NewRow();
drUsers["Name"] = "Manoj";
drUsers["Dept"] = "IT";
drUsers["Sal"] = 10000.00;
drUsers["ImageName"] = "flower1.bmp";

dtUsers.Rows.Add(drUsers);

drUsers = dtUsers.NewRow();
drUsers["Name"] = "Kiran";
drUsers["Dept"] = "IT";
drUsers["Sal"] = 11000.00;
drUsers["ImageName"] = "flower2.bmp";
dtUsers.Rows.Add(drUsers);

drUsers = dtUsers.NewRow();
drUsers["Name"] = "Mahesh";
drUsers["Dept"] = "HR";
drUsers["Sal"] = 7000.00;
drUsers["ImageName"] = "flower1.bmp";
dtUsers.Rows.Add(drUsers);

drUsers = dtUsers.NewRow();
drUsers["Name"] = "Suresh";
drUsers["Dept"] = "Pharma";
drUsers["Sal"] = 9000.00;
drUsers["ImageName"] = "flower2.bmp";
dtUsers.Rows.Add(drUsers);

return dtUsers;
}


In Row Command event of the grid write the below code


protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
Image imgUser = (Image)e.Row.FindControl("imgUser");
string imageName = drv["ImageName"].ToString();
imgUser.ImageUrl = "~/Images/"+imageName;
}
}

Comments or Responses

Login to post response