WinForms DataGridView,设置必选列
本文关键字:设置 DataGridView WinForms | 更新日期: 2023-09-27 18:18:29
我正在做一个windows窗体项目。在我的表单中,我有一个数据网格,每一行都必须填写一列。
我想获得类似于MS management Studio的东西:如果当前行的强制单元格未填充,我无法添加另一行。
我该怎么做呢?
使用CellValidiating
事件检查列的值。
像这样:
const int MandatoryColumnIndex = 1;
public Form1()
{
InitializeComponent();
dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
dataGridView1.RowValidating += new DataGridViewCellCancelEventHandler(dataGridView1_RowValidating);
}
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[MandatoryColumnIndex].FormattedValue.ToString() == string.Empty)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].Cells[MandatoryColumnIndex].ErrorText = "Mandatory";
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[MandatoryColumnIndex].ErrorText = string.Empty;
}
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == MandatoryColumnIndex)
{
if (e.FormattedValue.ToString() == string.Empty)
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "Mandatory";
e.Cancel = true;
}
else
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = string.Empty;
}
}
}