DataGridView RowsAdded 事件处理程序不工作?
DataGridView RowsAdded event handler not working?
当我的 DataGridView 有 1 行或多行时,我需要启用组合框。
我有以下未触发的代码。我正在使用 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
您的原始代码 (在您第一次编辑之前) 看起来像这样:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
comboBox1.Enabled = (e.RowCount > 1); // ? true : false;
}
e.RowCount
值报告您当前添加的行数,而不是 DataGridView
中恰好有多少行调用 Add()
.
换句话说,如果您重复调用 dataGridView1.Rows.Add(1)
,那么上面的代码每次都会禁用 comboBox1
,因为您不会一次添加 2 行或更多行。
相应地更改您的代码:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
comboBox1.Enabled = (e.RowCount > 0); // ? true : false;
}
此外,由于尝试添加任何 少于 行的内容将抛出 ArgumentOutOfRangeException
,您最好甚至不去检查 e.RowCount
.. . 它总是大于 0.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
comboBox1.Enabled = true;
}
当我的 DataGridView 有 1 行或多行时,我需要启用组合框。
我有以下未触发的代码。我正在使用 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
您的原始代码 (在您第一次编辑之前) 看起来像这样:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
comboBox1.Enabled = (e.RowCount > 1); // ? true : false;
}
e.RowCount
值报告您当前添加的行数,而不是 DataGridView
中恰好有多少行调用 Add()
.
换句话说,如果您重复调用 dataGridView1.Rows.Add(1)
,那么上面的代码每次都会禁用 comboBox1
,因为您不会一次添加 2 行或更多行。
相应地更改您的代码:
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
comboBox1.Enabled = (e.RowCount > 0); // ? true : false;
}
此外,由于尝试添加任何 少于 行的内容将抛出 ArgumentOutOfRangeException
,您最好甚至不去检查 e.RowCount
.. . 它总是大于 0.
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
comboBox1.Enabled = true;
}