如何将数据网格视图设置为不接受空值

本文关键字:设置 不接受 空值 视图 网格 数据 数据网 | 更新日期: 2023-09-27 18:30:41

我正在使用Windows表单c#。任何人都知道如何将DataGridView设置为不接受空值。因为我不希望用户插入空值.谢谢

如何将数据网格视图设置为不接受空值

您可以在代码中检查单元格的值为空或空:

foreach (DataGridViewRow dataRow in this.yourDataGridView.Rows)
{
  for (int index = 0; index < dataRow.Cells.Count; index++)
  {
    if (dataRow.Cells[index].Value == null || dataRow.Cells[index].Value == System.DBNull.Value || string.IsNullOrEmpty(dataRow.Cells[index].Value.ToString()))
    {
        // here is your logic...
    }
  } 
}

可以将 CellValueChanged 事件添加到 dataGridView 控件

 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null)
        {
            //Do something
        }
    }