简体   繁体   中英

Get selected row in DataGridView

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.

    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:

   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.

You can add your order_SelectionChanged after you clear selection in Form_Load() (not in InitializeComponents() )

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM