c# - DatagridView 选择最后一行

标签 c# 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)
    { }
}

当我执行这段代码时,我得到一个异常: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;

给出以下输出:(最后一行,滚动并选中)

alt text

关于c# - DatagridView 选择最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3810722/

相关文章:

c# - 我不明白基类的继承

c# - 具有多个 STA 线程的 Wpf 应用程序仍然阻塞用户界面

c# - 在 Windows 服务中使用 Thread.Sleep()

c# - 单用户访问数据库的建议

php - 任何易于使用的 php mysql datagrid?

C#单向链表实现

winforms - 如何从winforms c#中的datagridview中删除行指示器列

c# - 如何将mysql表中的数据添加到C#表单中

c# - DataGridView 复选框事件

string - "value of type datagridviewcell can not be converted to string"vb.net