I have a datagridview in my Winforms Application.
The user can click anywhere on the datagridview
And then click a button to perform an action on that datarow
However, in order to do this I need to recover the ID from that row
Now bearing in mind the user probably hasnt clicked the ID column
So SelectedCell.Value is no use to me here
I have tried the following code
DataGridViewRow row = dataIPs.SelectedRows[0];
DataGridViewCell cell = row.Cells[0];
string value = cell.Value.ToString();
But this produces an Out Of Bounds error.
How can I obtain the value from a specific column of the datagridview regardless of which column the user actually selects.
ANSWER
The code that worked for me in the end was as follows:
DataGridViewRow row = dataIPs.CurrentCell.OwningRow;
string value = row.Cells["IPID"].Value.ToString();
You appear to be trying to access the
SelectedRowscollection when no row has been selected.The default selection mode for the
DataGridViewisCellSelectand in this mode when you click on a cell no row is selected.You need to either change the selection mode or get the desired row some other way.
You can change the selection mode to
FullRowSelectwhich can be done in the designer or in code:Or you can access the selected cell and the row from that:
Or like this: