如何在grid view asp控件中显示图片?

How to display images in grid view asp control?

我使用数据table 作为网格视图的数据源。 数据的其中一列 table 必须显示图像。

以下是我创建数据的方式table:

DataTable dt = new DataTable();
List<ReportFeature> featureProps = fim.getFeatureProperties().ToList();

var headers = featureProps.FirstOrDefault().Properties.Select(k => k.Key).ToList();
headers.ForEach((h) => dt.Columns.Add(h, typeof(string)));

foreach (var feat in featureProps)
{
    DataRow row = dt.NewRow();
    foreach (var header in headers)
    {
        row[header] = feat.Properties[header];  
    }
    dt.Rows.Add(row);
}

下面是我如何将数据 table 绑定到网格视图数据源:

gvfeatureProps.DataSource = dt;
gvfeatureProps.DataBind();

数据中的一列 table 包含图像路径。 我的问题是如何在以编程方式绑定后让图像显示在我的网格视图中?

所有 <Columns> 也可以使用模板字段

使用 asp.net 图片:

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

或标准 HTML img:

<asp:TemplateField>
    <ItemTemplate>
        <img src='<%# Eval("MyImageUrlColumnName") %>' />
    </ItemTemplate>
</asp:TemplateField>

如果您需要比上一个答案中使用的 ImageField 更灵活一些。

如果您想以编程方式添加图像,请使用 RowDataBound 事件。

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;

        //create a new cell
        TableCell cell = new TableCell();

        //create an image
        Image img = new Image();
        img.ImageUrl = row["imageUrl"].ToString();

        //add the image to the cell
        cell.Controls.Add(img);

        //add the cell to the gridview
        e.Row.Controls.Add(cell);

        //or use addat if you want to insert the cell at a certain index
        e.Row.Controls.AddAt(0, cell);

        //or don't add a new cell but add it to an existing one (replaces original content)
        e.Row.Cells[2].Controls.Add(img);
    }
}