0

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;
1
  • try this example / tutorial - msdn.microsoft.com/en-us/library/aa479350.aspx pay attention to this line in the example dr["PictureURL"] = ResolveUrl("~/DisplayingImages/Images/Winter.jpg"); Commented Jun 9, 2015 at 15:29

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.