how to have one of the column in gridview to be an image?

I have a gridview that gets created in codebehind.

In the below code, I would like to have 3rd column to be some image (Example: PDF icon or similar).

I am thinking Type.GetType needs to be changed for column named “Image”??

DataTable dt = new DataTable();
GridView gview = new GridView();
DataRow dr;
DataColumn dc = new DataColumn("Description", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Image", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Size (MB)", Type.GetType("System.String"));
dt.Columns.Add(dc);
{
    dr = dt.NewRow();
    dr["Description"] = item["Name"];
    dr["Size (MB)"] = item["Size"];
    dr["Image"] = "pdf.gif"; // put complete reference here,
    dt.Rows.Add(dr);
}
gview.DataSource = dt;
gview.DataBind();
Controls.Add(gview);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Just store the image URL in the DataTable rather than the actual image. Then, use a TemplateField in your GridView and put an Image in the ItemTemplate:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageUrlColumn") %>' ... />
    </ItemTemplate>
</asp:TemplateField>

You can also use an ImageField:
<asp:ImageField DataImageUrlField="ImageNameColumn" DataImageUrlFormatString="/images/{0}"></asp:ImageField>

EDIT

When declaring columns, try this instead:

dt.Columns.Add("Image", typeof(string));

And to set the value of the image column, try this:
dr.SetField<string>("Image", "img.png");

Method 2

In grid view put command field column like the following

<asp:CommandField runat="server" ShowDeleteButton="true" ButtonType="Image" DeleteImageUrl="images/delete.png" ></asp:CommandField>

set the gridview property like the following

AutoGenerateDeleteButton=”false”

Method 3

Another way is to enable in your DataGrid the RowDataBound Event. Then set in the event the wire up for each new row to your image.

protected void GridView1_RowDataBound(object sender, GridViewRowWEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        //Setup in your image column index. By Example setting 0
        e.Row.Cells[0].Text=Server.HtmlDecode(@"<img src=""./Images/pdf.gif"" />");
    }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x