[英]How to display images in grid view asp control?
我將datatable用作網格視圖的數據源。 數據表的其中一列必須顯示圖像。
這是我創建數據表的方式:
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);
}
這是我將數據表綁定到網格視圖數據源的方式:
gvfeatureProps.DataSource = dt;
gvfeatureProps.DataBind();
數據表中的列之一包含圖像的路徑。 我的問題是,以編程方式綁定后,如何使圖像顯示在網格視圖中?
所有在<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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.