代码之家  ›  专栏  ›  技术社区  ›  Michael

如何在网格视图asp控件中显示图像?

  •  -1
  • Michael  · 技术社区  · 7 年前

    数据表的一列必须显示图像。

    下面是创建数据表的方法:

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

    数据表中的一列包含映像的路径。 我的问题是如何使图像在程序绑定后显示在网格视图中?

    2 回复  |  直到 7 年前
        1
  •  1
  •   VDWWD    7 年前

    如果要以编程方式添加图像,请使用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);
        }
    }
    
        2
  •  2
  •   spludlow    7 年前

    全部在内部 <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更大的灵活性。

    推荐文章