【问题标题】:How to change color of empty rows in a DataGridView?如何更改 DataGridView 中空行的颜色?
【发布时间】:2012-06-30 23:05:30
【问题描述】:

我正在尝试更改 DataGridView 中空行的颜色

foreach (DataGridViewRow r in dgv1.Rows)  
if (r.Value.ToString() == "")
//if (r.Cells.Value.ToString() == "") - also trying
r.DefaultCellStyle.BackColor = Color.WhiteSmoke;

但是 Row 没有 Value 的定义,Cells 需要通过 Column 来指定。
请问我该怎么做?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    好吧,您需要检查所有Cells。以下是使用 LINQ 的方法:

    foreach(DataGridViewRow r in dgv1.Rows) {
        if(r.Cells.All(c => c.Value.ToString() == string.Empty)) {
            r.DefaultCellStyle.BackColor = Color.WhiteSmoke;
        }
    }
    

    【讨论】:

    • 谢谢你,minitech。解决了,但应该是更简单的方法。
    【解决方案2】:
    foreach (DataGridViewRow r in dgv1.Rows)  
    if (r.Cells["YourImportantFieldNameLikeID"].Value == null)
    r.DefaultCellStyle.BackColor = Color.WhiteSmoke;
    

    如果您不想看到最后一个空行,可以使用以下命令禁用它:

    DataGridViewName.AllowUserToAddRows = False;
    

    【讨论】:

      猜你喜欢
      • 2011-01-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多