2017-04-20 191 views
1

我想检查datagridview的空单元格为空。因为我使用的是以下代码,但即使单元格已填满,它也会闪烁。检查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"); 
     } 
    } 

} 

哪里是错误..

在此先感谢...

+0

习惯上显示消息。但是我看到一个问题,单元格的值不会是'null',它会是'DbNull.Value' – Crowcoder

+0

当你认为它应该为空时,单元格的价值是什么?也许DbNull.Value? –

回答

0

首先要检查2个不同的东西:

e.ColumnIndexCurrentCell

它最好只使用1那么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/RowIndexCurrentCell不同,因为您刚刚离开它。如果你想检查点击,只需使用点击事件处理程序。

+0

我使用了你的建议,但即使有价值的单元格也能获得相同的响应信息。 – speedyraz

0

MSDN从 :

当细胞失去输入焦点,并且不再当前小区时发生。

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

为了得到正确的电池使用:

dataGridView1[e.ColumnIndex, e.RowIndex] 
0

的“CellLeave”活动将每次你从一个细胞导航时间解雇,如果您还没有输入到单元格,那么你不会得到一个在该单元格上“离开”事件。

如果你想检查编辑的单元格不是空的,那么你可能想使用'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"); 
      } 
     } 
+0

“cell.Value?.ToString()”,是“?”好或只是输入错误,我已经尝试过“cell.Value.ToString()”和geeting“NuLLRefrenceException被用户代码处理”。 – speedyraz

+0

'?'是C#6.0中的对象空检查器。 – Jegan

+0

我使用vs2010 ...所以任何兼容的解决方案... – speedyraz