C#DataGridView.Rows[i]问题
//清空现有DataGridView数据
while (this.dataGridView1.Rows.Count != 0)
{
this.dataGridView1.Rows.RemoveAt(0);
}
//dataGridView1.Rows.Clear();
modelList_quanxian = bll_quanxian.DataTableToList(bll_quanxian.GetAllList().Tables[0]);
for (int i = 0; i < modelList_quanxian.Count; i++)
{
model_quanxian = modelList_quanxian[i];
DataGridViewRow dr = new DataGridViewRow();
dataGridView1.Rows.Add(dr);
dataGridView1.Rows[i].Cells[0].Value = model_quanxian.QuanXianBianHao;
dataGridView1.Rows[i].Cells[1].Value = model_quanxian.QuanXianMingCheng;
}
说明一下,Count有很多行,问题在于我往DataGridView中添加时,会报出Row[i]索引值超出范围,必须为非负值,并小于集合大小。
“dataGridView1.Rows[i]”引发了“System.ArgumentOutOfRangeException”类型的异常-------导致的问题是,新增和修改操作,调用此方法,页面结果显示不全。做删除操作时,调用此方法能够显示全。请问各位高手如何解决。
[解决办法]
不明白你怎么会搞成这样,我把我自定义dataGridview控件里面的代码给你看下,反正用到现在还没问题暂时。
/// <summary> /// 在最后一笔添加新行 /// </summary> public void AddNewRow() { dataGridView1.Rows.Add(); int i = dataGridView1.Rows.Count - 1; dataGridView1.CurrentCell = dataGridView1[0, i]; // 强制显示该行 dataGridView1[0, i].Selected = true; //光标移至该行 } /// <summary> /// 删除最后一笔记录,或者选定的记录 /// </summary> public void DeleteRow() { if (dataGridView1.CurrentRow == null) return; dataGridView1.Rows.Remove(dataGridView1.CurrentRow); } /// <summary> /// 在选定的记录上面插入一笔记录 /// </summary> public void InsertRow() { if (dataGridView1.SelectedRows.Count >= 1) { int iIndex = dataGridView1.SelectedRows[0].Index; dataGridView1.Rows.Insert(iIndex, 1); } }
[解决办法]
是你cells超出范围不是rows
[解决办法]
while (this.dataGridView1.Rows.Count != 0) { dataGridView1.Rows.Clear(); }