0

I have a Web Image that I want to add to an ASP GridView. This is what I'm doing:

Image image = new Image();
image.ImageUrl = @"/_layouts/15/images/Project/x-mark-3-xxl.png";
row[course.CourseName] = image;

I get back the name of the object in the column. I'm doing a datatable and then binding it to the gridview, so the 'row' variable you see is obviously a row of the datatable. I need to show the image in the gridview. I did this a long time ago and I can't remember how I did it. And yes, it has to be by code.

1 Answer 1

1

You cannot put an image back into a row like that. You need the OnRowDataBound event and add the Image to a Cell directly.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //cast the row back to a datarowview
        DataRowView row = e.Row.DataItem as DataRowView;

        Image image = new Image();
        image.ImageUrl = @"/_layouts/15/images/Project/" + row["imageNameColumn"].ToString();

        //add the image to the gridview
        e.Row.Cells[0].Controls.Add(image);
    }
}

Or if you want to add the image at a later time, specify the Row and Cell by their index.

GridView1.Rows[4].Cells[2].Controls.Add(image);

Update

You can do this. Loop the cells and check if it is an Odd or Even cell and add the image.

for (int i = 0; i < e.Row.Cells.Count; i++)
{
    if (i % 2 == 1)
    {
        Image image = new Image();
        image.ImageUrl = @"/image.jpg";
        e.Row.Cells[i].Controls.Add(image);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works perfectly, but I have one more request. This is somewhat what my grid looks like: user | X | X | user2 | X | | user3 | | X | I need the X to be replaced by the images. Sorry I can't get the formatting correctly.
Updated my answer
Thank you so much! You have helped me a lot!

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.