簡體   English   中英

將圖像添加到數據表以在GridView asp.net中播放

[英]Add image to DataTable to diplay in GridView asp.net

我正在嘗試通過數據表綁定在GrIdView中顯示圖像,但它只是打印出純文本而不在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

默認情況下,GridView編碼單元格的HTML內容。

在網格ASPX標記中添加對RowDataBound事件處理程序的引用

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

然后添加以下代碼:

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);
    }
}

注意:在ASP.NET應用程序中,將物理路徑引用為IMG源不是一個好主意-它只能在您的開發機上工作。 將圖像放置在應用程序的子文件夾中,並使用相對的虛擬路徑。

哦,順便說一句,如果您的GridView中的列不是自動生成的,而是在網格的ASPX標記中定義的,則代替上述方法,可以簡單地將屬性htmlencode="false"到boundfield的聲明中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM