我在设置所选 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)
{ }
}
当我执行这段代码时,我得到一个异常:IndexOutOfRangeException occurred
: Index-1 does not have a value.
当我调试 Rows
集合和相应的 Cells
集合时,我看到两个集合都已填充。该索引也存在于 Rows 和 Cells 集合中。
我不知道我在这里做错了什么。有人可以帮我吗?谢谢
编辑:
这是完整的异常(exception):
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;
给出以下输出:(最后一行,滚动并选中)
关于c# - DatagridView 选择最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3810722/