stefan
stefan

Reputation: 439

Add image to DataTable to diplay in GridView asp.net

I'm trying to display an image in GrIdView through a datatable bind but its just printing out plain text and not displaying the picture in ie.

dt = new DataTable();

        dt.Columns.Add("Status", typeof(string));
        dt.Columns.Add("CRQ", typeof(String));
        dt.Columns.Add("Summary", typeof(String));
        dt.Columns.Add("Time", typeof(String));
        Session["TempTable"] = dt;
        GridView1.DataSource = dt;

        //

        //datat load
        dt = (DataTable)Session["TempTable"]; // Fetching datatable from session

        DataRow dr = dt.NewRow(); // Adding new row to datatable
        dr[0] = "<img src='C:\\Users\\josephs\\Desktop\\red.jpg' style='border-width:0px'/>";
        dr[1] = "CRQ000000000789";
        dr[2] = "Test CRQ Summary, example data";
        dr[3] = "WED 31/07/2013 16:00:00 PM";
        dt.Rows.Add(dr);

        DataRow dr2 = dt.NewRow(); // Adding new row to datatable
        dr2[0] = "<img src='C:\\Users\\josephs\\Desktop\\red.jpg' style='border-width:0px'/>";
        dr2[1] = "CRQ000000000889";
        dr2[2] = "Test another CRQ, example data";
        dr2[3] = "Tue 6/08/2013 14:00:00 PM";
        dt.Rows.Add(dr2);



        Session["TempTable"] = dt;   // update datatable in session
        GridView1.DataSource = dt;   // updated datatable is now new datasource
        GridView1.DataBind();        // calling databind on gridview

Upvotes: 0

Views: 3722

Answers (1)

Yuriy Galanter
Yuriy Galanter

Reputation: 39807

By default GridView encodes HTML content of a cell.

Add reference to RowDataBound event handler in your grid ASPX markup

<asp:gridview id="GridView1" 
        autogeneratecolumns="true"
        onrowdatabound="GridView1_RowDataBound" 
        runat="server">
</asp:gridview>

and then add following code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {

    if (e.Row.RowType == DataControlRowType.DataRow) {
       e.Row.Cells[0].Text = Server.HtmlDecode(e.Row.Cells[0].Text);
    }
}

Note: I it's not a good idea in an ASP.NET application to reference a physical path as an IMG source - it will work only on your dev machine. Place images in a subfolder of your application and use relative virtual path.

Oh and by the way, if columns in your GridView are not autogenerated and instead defined in the grid's ASPX markup then instead of above approach simple add property htmlencode="false" to boundfield's declaration:

<asp:boundfield datafield="Status"
            htmlencode="false"
            headertext="Status"/>

Upvotes: 3

Related Questions