nemostyle
nemostyle

Reputation: 814

How to change color of cells in grid when you have some conditions?

I want to change color of entire row(s) in grid. I have two check boxes above grid. One is Active, the another one is Inactive. When I click on active I want that all rows which ExpirationDate(name of the column in grid) is greater or equal than today DateTime turn from white color to grin. And when i click Inactive, same thing to red. That filters active and inactive are working, I just need to change color of the data row.

I know that I can use cell_formating event. Here is the code, but I need some help.

 private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        Color active = Color.LightGreen;
        Color inactive = Color.LightPink;

        DataRowView drv = bindingSource[e.RowIndex] as DataRowView;

        switch (drv["ExpirationDate"].ToString())
        {
            case ???:
                grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = active;
                break;
            case ???:
                grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = inactive;
                break;
        }
    }

I don't know what should I put in cases. Because, c# need constant value. When I put String.Format(" ExpirationDate>= '{0}' ", DateTime.Today) in case c# throw exception "Error 44 A constant value is expected". Any idea what should I type?

Upvotes: 1

Views: 153

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

No one forces you to use a switch, use an if...else when it's appropriate. But in this case you could simplify your code with the conditional operator:

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    Color active = Color.LightGreen;
    Color inactive = Color.LightPink;

    DataRowView drv = bindingSource[e.RowIndex] as DataRowView;
    bool isActive = drv.Row.Field<DateTime>("ExpirationDate").Date >= DateTime.Today;
    grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = isActive ? active : inactive;
}

I'm also using the DataRow extension method Field to cast the object to the right type DateTime instead of converting it to string which can cause localization issues.

Upvotes: 1

DrewJordan
DrewJordan

Reputation: 5314

I would use a bool, and do your check first, followed by an if-else. It's more readable, and more clearly expresses your intent.

private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    Color active = Color.LightGreen;
    Color inactive = Color.LightPink;

    DataRowView drv = bindingSource[e.RowIndex] as DataRowView;

    bool expired =
        DateTime.Parse(drv["ExpirationDate"].ToString()) < DateTime.Today;

    if (expired)
    {
        grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = inactive;
    }
    else
    {
        grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = active;
    }

} 

Upvotes: 1

Related Questions