简体   繁体   中英

Conditionally change row color on GridView

I'm trying to change the background color of table rows based on the value of a cell within the row on a webpage. Basically, I want to a check whether a case has been closed by seeing if the value stored on the table is null. If there is a date stored on the table, I want the row to turn gray.

When I use this, it will turn all of the rows gray instead of the ones that don't have a null value. I've checked the values of the table and they do contain nulls. The values stored in the caseClosedDate column are data type dates.

protected void CaseList_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    //table is generated through a stored procedure
    DataTable dt = mytable;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (DataRow row in dt.Rows)
        {
            //uses the column string name
            if(row["caseClosedDate"] != null)
            {
                e.Row.BackColor = Color.Gray;
            }
        }
    }
}

edit In case someone else is having a similar problem with the if statement, the table was populating the null values with "& nbsp;". The final answer is:

.case-closed { background-color:gray; }

}

protected void CaseList_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    //table is generated through a stored procedure
    DataTable dt = mytable;

    if (e.Row.Cells[6].Text.Trim() != " ")
    {
        e.Row.CssClass = "case-closed";
    }
}

You don't need to loop through the table, the values for the cells in the row are given to you in the even arguments.

if (e.Row.RowType == DataControlRowType.DataRow)
{
    //Change the number here to refer to the column you are checking
    if(string.IsNullOrEmpty(e.Row.Cells[1].Text))
    {
        e.Row.BackColor = Color.Gray;
    }
}

However, as pointed out by @im1dermike in the comments, it's much preferable to use CSS to achieve the colouring. So create a new CSS class for the colour:

.case-closed { background-color: gray; }

And instead of setting the colour in code, just set the CSS class:

e.Row.CssClass = "case-closed";

Use this in your OnRowDataBound Event if you are binding the data to the gridview.

if (DataBinder.Eval(e.Row.DataItem, "caseClosedDated") != null)
{
    e.Row.BackColor = Color.Gray;                
}

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