Get value in specific column in DataGridView
c#, datagridview, winforms
Solution
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;
Problem
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(); ```