DatagridView选择最后一行 [英] DatagridView Select last row

查看:430
本文介绍了DatagridView选择最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设置所选datagridview的最后一行时遇到一些麻烦。我以这种方式选择最后一行:

I have some trouble with setting the last row in my datagridview selected. I select the last row this way:

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发生:Index-1没有值。

When I execute this code I get an exception: IndexOutOfRangeException occurred: Index-1 does not have a value.

当我调试<$ c $时c>行集合和相应的 Cells 集合,我看到两个集合都已填满。该行索引也存在于行和单元格集合中。

When I debug the Rowscollection and the corresponding Cells collection I see both collections are filled. The index also exists of the Rows and Cells collection.

我不知道我在这里做错了什么。有人可以在这里帮助我吗? Thnx

I have no clue what I am doing wrong here. Someone who can help me out here? 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;

在输出后提供提示 :(最后一行,滚动并选中)

Gives following output: (Last row, scrolled and selected)

这篇关于DatagridView选择最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆