C# 以编程方式选择一行 DataGridView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13468388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:41:32  来源:igfitidea点击:

Selecting a row of DataGridView programmatically

c#winformsdatagridview

提问by user1837982

In my form application, there is a (buttonNEW) that selects NewIndexRowof DataGridViewand I want to change index of datagridview with this button.

在我的表单应用程序中,有一个 ( buttonNEW) 可以选择NewIndexRowDataGridView我想使用此按钮更改 datagridview 的索引。

private void buttonNew_Click(object sender, EventArgs e)
    {
        if (dataGridView.CurrentRow.Index!=dataGridView.NewRowIndex)
        {
            dataGridView.ClearSelection();
            dataGridView.Rows[dataGridView.NewRowIndex].Selected = true;
            label1.Text = dataGridView.CurrentRow.Index.ToString();

        }
    }

But after clicking the button the index of DataGridViewdoes not change. What is the problem?

但是点击按钮后索引DataGridView不会改变。问题是什么?

采纳答案by Derek

This should work :-

这应该有效:-

int numofRows = dataGridView.rows.count;

dataGridView.CurrentCell = dataGridView.Rows[numofRows - 1].Cells[0];

Or I think you could also do this :-

或者我认为你也可以这样做:-

dataGridView.CurrentCell = dataGridView.Rows[dataGridView.NewRowIndex].Cells[0];

回答by Carlos Landeras

Try with Linc:

尝试使用 Linc:

private void buttonNew_Click(object sender, EventArgs e)
    { 

     dataGridView.Rows.OfType<DataGridViewRow>().Last().Selected = true;

   }