【问题标题】:Can I change back color of gridview row which is programmatically databinding?我可以更改以编程方式进行数据绑定的 gridview 行的颜色吗?
【发布时间】:2014-01-21 14:13:52
【问题描述】:

我有一个这样的网格视图

<asp:GridView ID="GridView1" runat="server" 
    DataSourceID="SqlDataSource1">
</asp:GridView>

我将它绑定在 page_load 上

protected void Page_Load(object sender, EventArgs e)
{
    SqlDataSource1.SelectCommand = "select * from table"
}

在桌子上我有一个字段“日期”

+-----+
|date |
+-----+
|date1|
+-----+
|date2|
+-----+

我想做那个控制---> if date1

我是这样做的

protected void GridViewServicesList_RowDataBound(object sender, GridViewRowEventArgs e)
{
    DateTime date = 
        Convert.ToDateTime(e.Row.Cells[indexOfDateField].Text);//returns null!!!
    if(date < DateTime.Now)
    {
        e.Row.BackColor = Color.Red;
    }
}

这不起作用,我该怎么办? 首先我什至无法访问日期。我的意思是变量 DateTime 日期为空... 顺便一提 这不是我真正的代码,我写它是为了基本理解。

【问题讨论】:

  • 尝试设置单元格的背景颜色而不是行
  • 但日期为空,所以也不能这样做,我无法访问“日期”。也许我是在错误的事件??
  • 您确定date 为空吗?还是DateTime date = Convert.ToDateTime(e.Row.Cells[indexOfDateField].Text); 产生错误?
  • 是的,我确定它是 null 没有错误。
  • 可以在pre-render事件中遍历采集和更改。

标签: c# asp.net gridview


【解决方案1】:

如果 date1 标签在 TemplateField 中,请使用下面的示例。

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow) {
        //Reference the date1 label in Gridviews template field
        System.Web.UI.WebControls.Label date1 = (System.Web.UI.WebControls.Label)e.Row.FindControl("date1");
        GridViewRow myRow = e.Row;
        //set back color to green if incident category is hazard
        if (date1 < DateTime.Now)
             {
               e.Row.BackColor = Drawing.Color.SpringGreen;
            }   
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-01
    • 2018-01-08
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    相关资源
    最近更新 更多