【问题标题】:Gridview.RowdataBound not working on first rowGridview.RowdataBound 不适用于第一行
【发布时间】:2018-07-07 16:34:20
【问题描述】:

我有这段代码用于在 Gridview 的某些单元格中设置背景颜色,但我无法让它在第一行工作。

protected void GrdTask_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach(GridViewRow row in GrdTask.Rows)
        {
            if (Convert.ToInt32(e.Row.Cells[1].Text) == 0)
            {                   
                e.Row.Cells[1].Attributes["Style"] = "background-color: #f20713";
            }               
            if (Convert.ToInt32(e.Row.Cells[1].Text) <= -3)
            {
                e.Row.Cells[1].Attributes["Style"] = "background-color: #f4d942";
            }
            if (Convert.ToInt32(e.Row.Cells[1].Text) <= -5)
            {
                e.Row.Cells[1].Attributes["Style"] = "background-color: #28b779";
            }
        }          
    }

对于所有其余的行,它都可以正常工作。我做错了什么?

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    您正在循环 RowDataBound 事件中的行。您不需要这样做,并且会给出不正确的结果。 RowDataBound 事件已按行调用。最好使用 DataRowView 来获取正确的值并根据该值为单元格着色。

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //cast the row back to a datarowview
            DataRowView row = e.Row.DataItem as DataRowView;
    
            int cellValue = Convert.ToInt32(row["ColumnName"]);
    
            if (cellValue == 0)
            {
                e.Row.Cells[1].Attributes["style"] = "background-color: #f20713";
            }
            else if (cellValue <= -3)
            {
                e.Row.Cells[1].Attributes["style"] = "background-color: #f4d942";
            }
            else if (cellValue <= -5)
            {
                e.Row.Cells[1].Attributes["style"] = "background-color: #28b779";
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 2012-05-11
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 2017-01-07
      • 1970-01-01
      相关资源
      最近更新 更多