C# 检查datagridview单元格中的空值或空值

C# 检查datagridview单元格中的空值或空值,c#,datagridview,cells,C#,Datagridview,Cells,我想检查datagridview的空单元格。对于这一点,我使用以下代码,但它是闪烁的消息,即使单元格已填充 private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 5 || e.ColumnIndex == 6) { if (dataGridView1.CurrentCell.Value == null ||

我想检查datagridview的空单元格。对于这一点,我使用以下代码,但它是闪烁的消息,即使单元格已填充

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 5 || e.ColumnIndex == 6)
    {

        if (dataGridView1.CurrentCell.Value == null ||
            dataGridView1.CurrentCell.Value == DBNull.Value ||
            String.IsNullOrWhiteSpace(dataGridView1.CurrentCell.Value.ToString()))           
        {
            MessageBox.Show("Please enter  value");
        }
    }

}
错误在哪里


提前感谢…

首先,您正在检查两种不同的内容:

e、 ColumnIndex和CurrentCell

最好只使用其中的一个,这样CurrentCell就可以替换为:

dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]
因此,完整代码变成:

if ((e.ColumnIndex == 5 || e.ColumnIndex == 6) && e.RowIndex != -1)
{
    var cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

    if (cellValue == null || cellValue == DBNull.Value 
     || String.IsNullOrWhiteSpace(cellValue.ToString()))
    {
        MessageBox.Show("Please enter  value");
    }
}
注意:CellLeave事件会在您猜测它离开某个单元格时触发,选择另一个单元格,取消选择,等等。因此,e.ColumnIndex/RowIndex与您刚刚离开的CurrentCell不同。如果要检查单击,只需使用单击事件处理程序。

From :

当单元格失去输入焦点且不再是当前单元格时发生

这意味着dataGridView1.CurrentCell不再是您想要的单元格

要获得正确的单元格,请使用:

dataGridView1[e.ColumnIndex, e.RowIndex]

“CellLeave”事件将在您每次从单元格导航时触发,如果您尚未进入单元格,则该单元格上不会出现“leave”事件

如果要检查编辑的单元格是否为空,则可能需要使用“CellEndEdit”事件

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            var cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

            if (cell.Value == null || string.IsNullOrWhiteSpace(cell.Value.ToString()))
            {
                MessageBox.Show("Please enter some velue in cell");
            }
        }

人们习惯于显示信息。但是我看到一个问题,单元格的值不会为null,而是DbNull。value当你认为单元格的值应该为null时,它的值是多少?可能是DbNull.Value?cell.Value?ToString,是吗?确定或只是键入错误,我已尝试cell.Value.ToString和geeting NullReferenceException,但用户代码未处理该异常。“?”是C 6.0中的对象null检查器。确定,在这种情况下,use cell.Value==null | | string.IsNullOrWhiteSpacecell.Value.ToStringI已经这样做了,但是获取错误nullreferenceexception未经用户代码处理。。听起来像是“dataGridView1”为null,或者行[I]或列[I]为null。您能否在“var cell=…”行的断点处停止并检查对象?我使用了您的建议,但即使单元格有值,也会得到相同的响应,即消息。