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
Selecting a row of DataGridView programmatically
提问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) 可以选择NewIndexRow,DataGridView我想使用此按钮更改 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;
}

