简体   繁体   中英

Changing Color of DataGridView Rows

I'm having a problem with onDataRowBound. It seems that it put color on the whole column of cell[0]. The other cells has values on it but still it colors my cell. Here's my code.

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

What's wrong with this?

Add else block where you set cell's color to white (or some other color that your grid has by default)

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;
        }
        else
        {
            e.Row.BackColor = System.Drawing.Color.White;
        }
    }
}

EDIT: I think CSS styling would be better approach to do this. In your markup set CSS class to your rows and on RowDataBound event set another class as needed. Something like this:

define "normal" style in markup

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

and in your RowDataBound method set another class if cell values is empty string, like this:

e.Row.CssClass = "red-row";

You are checking Cell[0] values, what if you are changing in your backend database stored procedure and rearrange column name in select list, for example, you are having

BEFORE

SELECT Id,FirstName,LastName FROM EMPLOYEE

AFTER you/someone else change it to

SELECT Id,LastName,FirstName FROM EMPLOYEE

your code will be easily collapse, so its better to check DataItem of that row for values with name and based on that you can take decision. See code rewritten from your code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM