我有像这样的数据网格视图
当我尝试单击要尝试订购数据的列标题时,程序会在行中断行
DataGridViewRow row = dataGridView1.Rows[rowIndex];
未处理ArgumentOutOfRangeException。 指数超出范围。 必须是非负数且小于集合的大小。 参数名称:index
这是.designer.cs中的代码
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dataGridView1.BackgroundColor = System.Drawing.Color.Azure;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(21, 62);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.Size = new System.Drawing.Size(586, 381);
this.dataGridView1.TabIndex = 9;
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick_1);
这是我的.cs
中的代码private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
groupBoxPenghuni.Visible = false;
groupBoxStaff.Visible = false;
groupBoxRoom.Visible = false;
groupBoxDPenghuni.Visible = true;
groupBoxPenghasilan.Visible = false;
GroupBox_AddResident_Resident.Visible = false;
GroupBox_AddResident_Room.Visible = false;
GroupBox_AddResident1.Visible = false;
GroupBox_DeleteResident_Resident.Visible = false;
GroupBox_DeleteResident1.Visible = false;
GroupBox_Resident.Visible = false;
GroupBox_Update_Room.Visible = false;
GroupBox_UpdateResident1.Visible = false;
}
什么是错?我该怎么办?
答案 0 :(得分:4)
失败的原因是因为您的dataGridView1_CellContentClick_1
在您排序和Index was out of range
时会触发。你应该在继续之前检查它是否有效。
这些是声明的,但从未使用过。你真的需要这些线吗?
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
如果确实需要这些行,则必须先检查索引是否超出范围,然后再尝试声明它们。
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
int rowIndex = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[rowIndex];
groupBoxPenghuni.Visible = false;
groupBoxStaff.Visible = false;
groupBoxRoom.Visible = false;
groupBoxDPenghuni.Visible = true;
groupBoxPenghasilan.Visible = false;
GroupBox_AddResident_Resident.Visible = false;
GroupBox_AddResident_Room.Visible = false;
GroupBox_AddResident1.Visible = false;
GroupBox_DeleteResident_Resident.Visible = false;
GroupBox_DeleteResident1.Visible = false;
GroupBox_Resident.Visible = false;
GroupBox_Update_Room.Visible = false;
GroupBox_UpdateResident1.Visible = false;
}
}
答案 1 :(得分:0)
你必须检查CellContentClick事件:
if (e.RowIndex != -1 && e.ColumnIndex!=-1)
{
// do something
}
如果e.RowIndex为-1,则表示您单击了列标题 行标题
也是如此