DataGridView RowsAdded事件处理程序无法正常工作?

时间:2015-04-16 01:54:10

标签: c# datagridview

当我的DataGridView有一行或多行时,我需要一个comboBox来启用。

我有以下不触发的代码。我正在使用dataGridView1.Rows.Add(...)方法向DataGridView添加行。

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
   comboBox1.Enabled = (e.RowCount > 1); // ? true : false; Thanks Blogbeard  -- Changed back to (e.RowCount > 1) to show my error.
}

问题:

为什么这不起作用?

有更好的方法吗?我应该使用另一个事件处理程序吗?

编辑:

Form1.Designer.cs中的事件处理程序订阅:

this.dataGridView1.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.dataGridView1_RowsAdded);

VS 2010中的屏幕截图,显示事件处理程序应该注册到我的DGV

enter image description here

1 个答案:

答案 0 :(得分:4)

您的原始代码(首次修改之前)如下所示:

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
   comboBox1.Enabled = (e.RowCount > 1); // ? true : false;
}

e.RowCount值会报告您当前正在添加的行数,在调用DataGridView时恰好有多少行Add() 1}}。

换句话说,如果您反复拨打dataGridView1.Rows.Add(1),则上述代码每次都会停用comboBox1,因为您一次不会添加2行或更多行。

相应地更改您的代码:

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
   comboBox1.Enabled = (e.RowCount > 0); // ? true : false;
}

此外,由于尝试添加 less 而不是1行的任何内容会引发ArgumentOutOfRangeException,因此您甚至不必费心检查e.RowCount ...它' ll总是大于0。

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
   comboBox1.Enabled = true;
}