Datagridview Cell Style问题

时间:2012-11-29 06:43:18

标签: c# datagridview

我在C#桌面应用程序中有一个Datagridview。当任何一个单元格为空时,为了突出显示它,我将该特定单元格的背景更改为Color.Green

                if (checkString(Convert.ToString(this.UserDataTable.Rows[i].Cells[kk].Value).Trim()) == false)
                {
                    this.UserDataTable.Rows[i].Cells[kk].Style.BackColor = Color.Green;
                    this.MandatoryField_Label.ForeColor = Color.Green;
                    success = false;
                }

当用户在单元格中输入数据时,我会恢复更改。知道如何做到这一点。

其中一个解决方案,我想的是检查每个单元格颜色然后更改它。我相信,有一种更好的方法可以做到。

这不起作用:

 this.UserDataTable.DefaultCellStyle.BackColor = Color.White;

由于

2 个答案:

答案 0 :(得分:0)

您可以在CellLeave事件

上检查单元格的内容
if(!string.IsNullOrEmpty(((DataGridViewCell)sender).Value))
    ((DataGridViewCell)sender).Style.BackColor = Color.White;

答案 1 :(得分:0)

处理此问题最简洁的方法可能是使用CellFormatting事件(这是您需要的唯一代码,您可以删除其他代码):

dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.Value == null || String.IsNullOrWhiteSpace(e.Value.ToString()))
    {
        e.CellStyle.BackColor = Color.Green;
    }
    else
    {
        e.CellStyle.BackColor = Color.White;
    }            
}