Reputation: 5417
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.
The code that worked for me in the end was as follows:
DataGridViewRow row = dataIPs.CurrentCell.OwningRow;
string value = row.Cells["IPID"].Value.ToString();
Upvotes: 4
Views: 41192
Reputation: 329
You can also try to add a column with buttons in your datagridview. after that you can catch an event "CellContentClick" from your datagridview, which has "RowIndex" and "ColumnIndex" properties in eventargs.
Upvotes: 0
Reputation: 33183
You appear to be trying to access the SelectedRows
collection when no row has been selected.
The default selection mode for the DataGridView
is CellSelect
and 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 FullRowSelect
which can be done in the designer or in code:
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Or you can access the selected cell and the row from that:
DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex];
Or like this:
DataGridViewRow row = dataGridView1.CurrentCell.OwningRow;
Upvotes: 3
Reputation: 85
Set the SelectionMode property to FullRowSelect. This is needed for SelectedRow to work
Upvotes: 0