将图像添加到datatable或gridview

时间:2013-07-17 13:52:30

标签: c# asp.net

我有一个绑定到gridview的数据表。列是可变的,所以我想利用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" };
}

3 个答案:

答案 0 :(得分:1)

您可以使用 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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

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

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

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

那就是说,RowDataBound可能是你想要的事件。

RowDataBound事件将始终为您提供一个非null的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。

相关问题