Search code examples
c#datagridviewdatagridviewcolumn

How can I get the value of a given column for the selected row in a DataGridView?


Knowing the name of the column to be queried, how can I extract the value from that column for the currently selected record in a DataGridView?

IOW, if I have a DataGridView with columns named id, Date, Time, Space, and I want the value of the Space column for the currently selected row, how can I assign that value to a String variable?

In pseudocode, I would expect it to be something like:

String s = dataGridView1.CurrentRow["Space"].ToString();

...but I'm sure it's not really that straightforward.

UPDATE

The answers look good, but is there a way to get the value from the current row that doesn't respond to a dataGridView event? I need to assign the value apart from the dataGridView being clicked or any other event. IOW: is there a way to get the current row?


Solution

  • You can use

    dataGridView1.CurrentRow.Cells[yourColumn] 
    

    to access the current row if there is one.. ..and even if you have MultiSelect on, you can always use

    dataGridView1.SelectedRows[0].Cells[yourColumn] 
    

    to access the first selected row..