简体   繁体   English

如何在datagridview中更改行的颜色C#

[英]How to change color of row in datagridview c#

I have this part of code, but not working.. 我有这部分代码,但无法正常工作。

       foreach (DataGridViewRow row in dg1.Rows)
        {
            var now = DateTime.Now.Day;
            var expirationDate = DateTime.Parse(row.Cells[2].Value.ToString()).Day;

            if (now == expirationDate)
            {
                row.DefaultCellStyle.BackColor = Color.Red; 
            }
        }

Not good idea to compare classes/structs like that(with == operator) 比较像这样的类/结构(用==运算符)不是一个好主意

try using 尝试使用

if(DateTime.Compare(now, expirationDate) == 0)

Your problem is not the comparison you're performing (as others are referring), but it would be better to compare Date using DateTime.Compare method. 您的问题不是正在执行的比较(正如其他人所指),但是使用DateTime.Compare方法比较Date会更好。

The problem is you're not checking for NewRow . 问题是您不检查NewRow It causes exception when you try to read an empty Row . 当您尝试读取空Row时,它将导致异常。

foreach (DataGridViewRow row in dg1.Rows)
{
    if (!row.IsNewRow)
    {
        //your code
    }
}

Have you tried replacing foreach with for ? 您是否尝试将foreach替换for

for (int i = 0; i < dg1.Rows.Length; i++)
    {
        var now = DateTime.Now.Day;
        var expirationDate = DateTime.Parse(dg1.Rows[i].Cells[2].Value.ToString()).Day;

        if (now == expirationDate)
        {
            dg1.Rows[i].DefaultCellStyle.BackColor = Color.Red; 
        }
    }

The collection used in foreach is immutable. foreach使用的集合是不可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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