C# 如何在网格视图asp控件中显示图像?
我使用datatable作为网格视图的数据源。 数据表的一列必须显示图像 以下是创建数据表的方法:C# 如何在网格视图asp控件中显示图像?,c#,asp.net,.net,gridview,C#,Asp.net,.net,Gridview,我使用datatable作为网格视图的数据源。 数据表的一列必须显示图像 以下是创建数据表的方法: DataTable dt = new DataTable(); List<ReportFeature> featureProps = fim.getFeatureProperties().ToList(); var headers = featureProps.FirstOrDefault().Properties.Select(k => k.Key).ToList(); he
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);
}
数据表中的一列包含图像的路径。
我的问题是,通过编程绑定后,如何在网格视图中显示图像?全部在
中您也可以使用模板字段
使用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);
}
}
您可以将列表
featureProps
直接绑定到GridView。无需将其转换为数据表。请参见属性名称被用作默认列标题。如果属性名不应该是列标题,您只需要更改该行为。您的意思是列名可以更改吗?谢谢您的帖子!如何访问GridView1_RowDataBound事件中单元格的文本?您不必使用row[“columnName”]
是的,我知道。但我需要从GridView1_RowDataBound事件中的每个单元格获取文本,以获取imageUrle.Row.Cells[I].text
,这是一个不间断的空格。但这意味着一个空牢房。
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);
}
}