【问题标题】:add image to datatable or gridview将图像添加到数据表或网格视图
【发布时间】:2013-07-17 13:52:30
【问题描述】:

我有一个绑定到网格视图的数据表。这些列是可变的,所以我想利用 AutoGeneratedColumns。我想在某些条件下绑定图像。我需要做什么?

void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    DataRowView drv = e.Row.DataItem as DataRowView;
    if (drv != null)
        drv[1] = new HtmlImage() { Src = "add.png" };
}

【问题讨论】:

标签: c# asp.net


【解决方案1】:

听起来 AutoGeneratedColumns 属性在这里对您没有帮助,因为列类型适用于整个 GridView;它们不是按行计算的。

您也许可以使用带有数据绑定的TemplateField 来有条件地格式化每一行的字段,而无需编写任何代码。

如果这不能为您完成,我想您将不得不编写代码。请记住,当创建行时,RowCreated 事件总是会触发(回发事件),但只会在 GridView 实际转到其 DataSource 进行数据绑定时为您提供非空 DataItem (e.Row.DataItem);如果 GridView 已缓存其呈现状态(在 ViewState 中),则数据项将为空。此时,您只能通过执行以下操作来访问行的主键字段:var keys = myGridView.DataKeys[rowIndex];(主键字段由您为 GridView 的 DataKeyNames 属性提供的值确定,并存储在 ViewState 中,因此您可以在回发时访问它们。)

在修改某种类型的 DataBoundField 的列时也要小心(就像大多数字段一样);由于 RowDataBound 事件发生在 RowCreated 事件之后,因此当 RowDataBound 被触发时,您在 RowCreated 事件处理程序中对行/单元格内容所做的任何手动更改都将被数据绑定破坏

也就是说,RowDataBound 可能是您想要的事件。

RowDataBound 事件将始终为您提供非空 DataItem,但仅在发生真正的数据绑定时触发(与 ViewState 中的“绑定”相反);所以通常这个事件在回发时根本不会触发。不过没关系,因为 GridView 会为您记住它的状态。

如果你必须使用代码,它应该看起来像这样:

//don't forget to attach this event handler, either in markup 
//on the GridView control, in code (say, in the Page_Init event handler.)
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
  //HtmlImage gives you a plain-vanilla <img> tag in the HTML.  
  //If you need to handle some server side events (such as Click)
  //for the image, use a System.Web.UI.WebControls.Image control
  //instead.
  HtmlImage img = new HtmlImage() { Src = "path/to/image.jpg" };
  e.Row.Cells[1].Controls.Add(img);
}

但是,说真的,请先检查 TemplateField。

【讨论】:

    【解决方案2】:

    您可以使用 RowDataBound 事件来处理每一行:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
          if (e.Row.RowType == DataControlRowType.DataRow)
          {
               DataRowView drv = e.Row.DataItem as DataRowView;
               if (drv != null)
               {
                   // your code here...
               }
          }
    }
    

    有关此活动的更多信息,请参阅here

    【讨论】:

      【解决方案3】:

      这应该可行,它使用实际单元格的控件:

      void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
      {
          HtmlImage img = new HtmlImage() { Src = "add.png" };
          e.Row.Cells[1].Controls.Add(img);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 2014-07-22
        • 1970-01-01
        • 2017-11-03
        • 1970-01-01
        相关资源
        最近更新 更多