C# 当您有一些条件时,如何更改网格中单元格的颜色?

C# 当您有一些条件时,如何更改网格中单元格的颜色?,c#,C#,我想更改网格中整行的颜色。我在网格上方有两个复选框。一个处于活动状态,另一个处于非活动状态。当我单击active时,我希望ExpirationDate(网格中列的名称)大于或等于today DateTime的所有行从白色变为绿色。当我点击Inactive时,同样的东西变成红色。如果活动和非活动的过滤器都在工作,我只需要更改数据行的颜色 我知道我可以使用单元格格式化事件。这是代码,但我需要一些帮助 private void grid_CellFormatting(object sender, D

我想更改网格中整行的颜色。我在网格上方有两个复选框。一个处于活动状态,另一个处于非活动状态。当我单击active时,我希望ExpirationDate(网格中列的名称)大于或等于today DateTime的所有行从白色变为绿色。当我点击Inactive时,同样的东西变成红色。如果活动和非活动的过滤器都在工作,我只需要更改数据行的颜色

我知道我可以使用单元格格式化事件。这是代码,但我需要一些帮助

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

我不知道我应该在箱子里放什么。因为,c需要常量。当我把
String.Format(“ExpirationDate>='{0}',DateTime.Today)
放在c#throw exception“Error 44中,需要一个常量”。知道我应该键入什么吗?

没有人强迫您使用
开关,在适当的时候使用
if…else
。但在这种情况下,您可以使用条件运算符简化代码:

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;
}
private void grid\u CellFormatting(对象发送方、DataGridViewCellFormattingEventArgs e)
{
激活颜色=Color.LightGreen;
Color inactive=Color.LightPink;
DataRowView drv=bindingSource[e.RowIndex]作为DataRowView;
bool isActive=drv.Row.Field(“ExpirationDate”).Date>=DateTime.Today;
grid.Rows[e.RowIndex].DefaultCellStyle.BackColor=isActive?active:inactive;
}

我还使用
DataRow
扩展方法将对象强制转换为正确的类型
DateTime
,而不是将其转换为
string
,这可能会导致本地化问题。

我会使用bool,首先进行检查,然后执行
if-else
。它更具可读性,更清楚地表达了你的意图

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

} 
private void grid\u CellFormatting(对象发送方、DataGridViewCellFormattingEventArgs e)
{
激活颜色=Color.LightGreen;
Color inactive=Color.LightPink;
DataRowView drv=bindingSource[e.RowIndex]作为DataRowView;
布尔过期了=
Parse(drv[“ExpirationDate”].ToString())
由于您需要固定的案例来执行
切换
,因此将其改为
if
/
else
语句。Tnx,这就是我所需要的全部…:)您的方法也是正确的,与Tim Schmelter的方法非常相似。非常感谢你。