C# 当gerate单击空gridview列表中的按钮时崩溃

C# 当gerate单击空gridview列表中的按钮时崩溃,c#,gridview,C#,Gridview,当我使用以下代码在gridview中单击时: dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(0, 0)); 在空的gridview上,会发生以下错误: "An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Index w

当我使用以下代码在gridview中单击时:

 dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(0, 0));
在空的gridview上,会发生以下错误:

"An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Index was out of range. Must be non-negative and less than the size of the collection."
在这一行代码中:

 DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
我的问题是如何避免这个错误?
谢谢大家!

在您的
dataGridView1\u单元格单击
,您需要检查索引是否大于零,然后才能尝试从
访问元素

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
 {
       //Don't want this to execute when the column header/row is clicked (OOB)
        if (e.RowIndex < 0 || e.ColumnIndex < 0)
              return;

        DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
 }
private void dataGridView1\u CellClick(对象发送者,DataGridViewCellEventArgs e)
{
//不希望在单击列标题/行时执行此操作(OOB)
如果(e.RowIndex<0 | | e.ColumnIndex<0)
返回;
DataGridViewRow行=this.dataGridView1.Rows[e.RowIndex];
}

在您的
dataGridView1\u单元格单击
,您需要检查索引是否大于零,然后才能尝试从
访问元素

 private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
 {
       //Don't want this to execute when the column header/row is clicked (OOB)
        if (e.RowIndex < 0 || e.ColumnIndex < 0)
              return;

        DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
 }
private void dataGridView1\u CellClick(对象发送者,DataGridViewCellEventArgs e)
{
//不希望在单击列标题/行时执行此操作(OOB)
如果(e.RowIndex<0 | | e.ColumnIndex<0)
返回;
DataGridViewRow行=this.dataGridView1.Rows[e.RowIndex];
}
不要调用
DataGridView
a
GridView
DataGrid
!!这是错误和混乱的,因为这些是不同的控件。总是用正确的名字来称呼事物!是的,再打四个字母您需要检查e.RowIndex!标题可以是-1。不要调用
DataGridView
a
GridView
DataGrid
!!这是错误和混乱的,因为这些是不同的控件。总是用正确的名字来称呼事物!是的,再打四个字母您需要检查e.RowIndex!标题可以是-1。