C# – Get selected row in DataGridView

cdatagridviewselection

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.

Best Answer

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