C# WinForms DataGridView,设置必填列
我正在做一个windows窗体项目。在我的表单中,我有一个datagrid,它的每一行都必须填写一列 我想获得类似于MS-management-Studio的内容:如果当前行中的必填单元格未填充,则无法添加其他行C# WinForms DataGridView,设置必填列,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我正在做一个windows窗体项目。在我的表单中,我有一个datagrid,它的每一行都必须填写一列 我想获得类似于MS-management-Studio的内容:如果当前行中的必填单元格未填充,则无法添加其他行 如何执行此操作?使用CellValidiating事件检查列的值 大概是这样的: const int MandatoryColumnIndex = 1; public Form1() { InitializeComponent();
如何执行此操作?使用
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;
}
}
}
使用
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;
}
}
}
我正在尝试你的一段代码,但有点错误:如果我编辑必填单元格,它会工作,但是如果我只填充其他单元格,将必填单元格保留为空,我可以添加我想要的所有行。这不好,您也可以使用
RowValidating
事件。我修改了代码以显示一个示例。太好了!它起作用了!非常感谢。(我只使用行验证
事件解决了这个问题)我正在尝试你的代码,但有一个问题:如果我编辑了必填单元格,它会工作,但是如果我只填充其他单元格,将必填单元格保留为空,我可以添加我想要的所有行。这不好,您也可以使用RowValidating
事件。我修改了代码以显示一个示例。太好了!它起作用了!非常感谢。(我仅使用RowValidating
事件解决了此问题)