C# 更改DataGridView行的颜色

C# 更改DataGridView行的颜色,c#,asp.net,datagridview,C#,Asp.net,Datagridview,我对onDataRowBound有问题。似乎它为单元格[0]的整个列添加了颜色。其他单元格上有值,但它仍然为我的单元格着色。这是我的密码 protected void GridUserMessage_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (String.IsNullOrWhiteSpace

我对onDataRowBound有问题。似乎它为单元格[0]的整个列添加了颜色。其他单元格上有值,但它仍然为我的单元格着色。这是我的密码

protected void GridUserMessage_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (String.IsNullOrWhiteSpace(e.Row.Cells[0].Text))
        {
            e.Row.BackColor = System.Drawing.Color.Red;
        }
    }
}

这有什么问题?

添加
其他
块,将单元格颜色设置为白色(或网格默认的其他颜色)

编辑: 我认为CSS样式将是更好的方法来做到这一点。 在标记中将CSS类设置为行,并在
RowDataBound
事件中根据需要设置另一个类。大概是这样的:

e.Row.CssClass = "red-row";
在标记中定义“普通”样式

<asp:GridView runat="server" RowStyle="normal-row" ...>

您正在检查单元格[0]值,如果您正在更改后端数据库存储过程并在选择列表中重新排列列名,例如,您正在

以前

SELECT Id,FirstName,LastName FROM EMPLOYEE
在您/其他人将其更改为

SELECT Id,LastName,FirstName FROM EMPLOYEE
您的代码将很容易崩溃,因此最好检查该行的DataItem,以查找具有名称的值,并根据这些值做出决定。请参阅从代码重写的代码

 protected void GridUserMessage_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
  // Check database column has value or not.  
  if(String.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ColumnNameOfDataYouWantToCheck")))
    {
        e.Row.BackColor = System.Drawing.Color.Red;
    }
 }
}
 protected void GridUserMessage_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
  // Check database column has value or not.  
  if(String.IsNullOrEmpty(Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ColumnNameOfDataYouWantToCheck")))
    {
        e.Row.BackColor = System.Drawing.Color.Red;
    }
 }
}