C# 获取 DataGridView 中的选定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12138248/
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
Get selected row in DataGridView
提问by Igor
ALL,
全部,
I have a DataGridView control on my WinForms application with the selection property as "Entire Row" and no multi-selection. I also attach the SelectionChanged delegate to it, where I need to get the currently selected row.
我的 WinForms 应用程序上有一个 DataGridView 控件,其选择属性为“整行”并且没有多选。我还将 SelectionChanged 委托附加到它,我需要在其中获取当前选定的行。
private void order_SelectionChanged(object sender, EventArgs e)
{
ordersItemIndex = order.SelectedRows[0].Index;
}
Problem is, when the program starts, there should be no selection at all and only later user can change the selection with mouse or keyboard. So in my Form_Load() event I have this:
问题是,当程序启动时,根本不应该有选择,只有以后的用户才能用鼠标或键盘更改选择。所以在我的 Form_Load() 事件中,我有这个:
order.ClearSelection();
However, this code path throws an exception on the start-up of the program.
但是,此代码路径在程序启动时抛出异常。
Is there a nice way to tell the program "We are loading the form, don't call the delegate", without any additional variable?
有没有一种很好的方法来告诉程序“我们正在加载表单,不要调用委托”,而不需要任何额外的变量?
Thank you.
谢谢你。
采纳答案by JleruOHeP
You can add your order_SelectionChanged after you clear selection in Form_Load()(not in InitializeComponents())
您可以在Form_Load()(not in InitializeComponents()) 中清除选择后添加您的 order_SelectionChanged
But better check in your handler is there any selected rows.
但最好检查您的处理程序是否有任何选定的行。
private void order_SelectionChanged(object sender, EventArgs e)
{
if (order.SelectedRows.Count > 0)
ordersItemIndex = order.SelectedRows[0].Index;
}

