DatagridView选择最后一行

我在设置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) { } } 

当我执行此代码时,我得到一个exception: 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) 

尝试:

 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; 

提供以下输出 :(最后一行,滚动和选中)

替代文字

我知道这可能有点晚,但它可能对其他人有用。

你试过这个:

grid.Rows.Row[grid.Rows.Count -1].Selected = true;

在我的Windows应用程序中,我首先在我的datagridview中使用了你的代码并得到了相同的exception..然后当我在床上的时候它来到了我(我是编程的新手)。

如果我写为: Rows[Rows.count-1]第一行是“0”和“0-1 = -1”所以它超出范围:)

然后,当我将我的代码更改为Rows.Row[index]它工作了! 🙂


如果使用c#3.0及更高版本,请选择另一种方法:检查CellAddress(); ;)

诚挚

你有没有考虑过使用Linq?

  grid.Rows.OfType().Last().Selected = true; grid.CurrentCell = grid.Rows.OfType().Last().Cells.OfType().First(); // if first wanted 

IndexOutOfRangeException的’catch’块为空,并且根本不会显示任何错误。

要么你的问题不准确,要么在其他地方抛出exception。

编辑:看了你添加的调用堆栈,我可以看到错误确实没有被抛出,而是在CurrencyManager类的Current / Item属性中,最终由对CurrentCell setter的调用触发。

底线:问题不在此代码中; 由您设置当前单元格触发的其他一些代码抛出了exception。

 dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true; 

最后一行是空的,因为它是用户可以添加新行的空行。 无法选择此行。 你试过grid.Rows.Count – 2吗? 或者,您可以将AllowUserToAddRows设置为false。