我在设置datagridview中的最后一行时遇到了一些麻烦.我这样选择最后一行:
if (grid.Rows.Count > 0)
{
try
{
grid.Rows[grid.Rows.Count - 1].Selected = true;
grid.CurrentCell = grid.Rows[grid.Rows.Count - 1].Cells[1]
}
catch (IndexOutOfRangeException)
{ }
catch (ArgumentOutOfRangeException)
{ }
}
Run Code Online (Sandbox Code Playgroud)
当我执行此代码时,我得到一个异常IndexOutOfRangeException occurred:: Index-1没有值.
当我调试Rows集合和相应的Cells集合时,我看到两个集合都已填充.该索引还存在Rows和Cells集合.
我不知道我在这里做错了什么.谁可以帮助我在这里?日Thnx
编辑:
这是完整的例外:
System.IndexOutOfRangeException: Index -1 does not have a value.
at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)
at System.Windows.Forms.CurrencyManager.get_Current()
at System.Windows.Forms.DataGridView.DataGridViewDataConnection.OnRowEnter(DataGridViewCellEventArgs e)
at System.Windows.Forms.DataGridView.OnRowEnter(DataGridViewCell& dataGridViewCell, Int32 columnIndex, Int32 rowIndex, Boolean canCreateNewRow, Boolean validationFailureOccurred)
at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
at System.Windows.Forms.DataGridView.set_CurrentCell(DataGridViewCell value)
Run Code Online (Sandbox Code Playgroud)
KMå*_*Mån 14
尝试:
dataGridView1.ClearSelection();//If you want
int nRowIndex = dataGridView1.Rows.Count - 1;
int nColumnIndex = 3;
dataGridView1.Rows[nRowIndex].Selected = true;
dataGridView1.Rows[nRowIndex].Cells[nColumnIndex].Selected = true;
//In case if you want to scroll down as well.
dataGridView1.FirstDisplayedScrollingRowIndex = nRowIndex;
Run Code Online (Sandbox Code Playgroud)
提供以下输出 :(最后一行,滚动和选中)

IndexOutOfRangeException 的“catch”块为空,并且根本不会显示任何错误。
要么你的问题不准确,要么异常被抛出到其他地方。
编辑:查看了您添加的调用堆栈后,我可以看到错误确实不是在这里抛出的,而是在CurrencyManager类的Current/Item属性中抛出的,这最终是由对CurrentCellsetter 的调用触发的。
底线:问题不在这段代码中;该异常是由您设置当前单元格触发的其他一些代码引发的。
| 归档时间: |
|
| 查看次数: |
55426 次 |
| 最近记录: |