Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the selected row data from a data grid view using SelectedRows?

I have a table that I am displaying in a data grid view control. The user selects a single row from the control and presses a button. I need to retrieve the cells from that row and store them as strings.

Exactly how do I get the data using the SelectedRow method? I've been working on this for several hours and I'm at the end of my rope. Here's an example of something I've tried:

DataGridViewCellCollection selRowData = dataGridView1.SelectedRows[0].Cells;

If I try to access selRowData[x], the return value does not contain my data.

like image 682
Andrew Avatar asked Aug 23 '10 23:08

Andrew


People also ask

How do I get the index of a selected row?

You can get the selected row indexes by using the selectedRowsIndexes property in Grid.


2 Answers

You're close - you need to reference each Cell through its index and return its Value property:

string firstCellValue = dataGridView1.SelectedRows[0].Cells[0].Value;
string secondCellValue = dataGridView1.SelectedRows[0].Cells[1].Value;

etc.

like image 113
Jay Riggs Avatar answered Sep 21 '22 01:09

Jay Riggs


If you want the data and the data is likely bound to an datasource, then might I suggest that you get the key from the selection, and then you can use that to access the data any way you like:

dataGridView.SelectedDataKey.Value;
like image 30
Rob_vH Avatar answered Sep 21 '22 01:09

Rob_vH