Adding image to GridView created in CodeBehind

5.5k Views Asked by At

First thing I do is create a Datatable and then bind it to a GridView
Here is my code

 DataTable dt = new DataTable();
 DataColumn imgC = dt.Columns.Add("img", typeof(string));
 DataRow  row1 = dt.NewRow();
 row1["img"] = "~images/foo.png";

 GridView gv = new GridView();
 gv.DataSource = dt;
 gv.DataBind();
 cust_services.Controls.Add(gv);

I'm not sure where to go from here, as it just displays text, I have tried creating an Image and just writing

row1["img"] = img;
2

There are 2 best solutions below

0
On BEST ANSWER

You can make use of <asp:ImageField/> within the the Gridview to achieve this. So your markup will look like

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:ImageField DataImageUrlField="Value" ControlStyle-Width="100" ControlStyle-Height="100" HeaderText="My Image" />
    </Columns>
</asp:GridView>

In your C# code you can use List to add the images. So something as simple as

List<ListItem> files = new List<ListItem>();
files.Add(new ListItem("~/Images/SomeImage.jpg"));

GridView2.DataSource = files;
GridView2.DataBind();

This will only add one image to the grid. If you want to add all the images to the grid that are in a particular directory then just use a foreach loop.

string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
    List<ListItem> files = new List<ListItem>();
    foreach (string filePath in filePaths)
    {
        string fileName = Path.GetFileName(filePath);
        files.Add(new ListItem(fileName, "~/Images/" + fileName));
    }
    GridView2.DataSource = files;
    GridView2.DataBind();
0
On

Your binding is correct but you need to bind the image to an ImageField in your GridView as well.

<asp:ImageField DataImageUrlField="BoundName"></asp:ImageField>