views:

82

answers:

4

It's that simple. How do I get the index of the currently selected Row of a DataGridView? I don't want the Row object, I want the index (0 .. n).

+1  A: 
dataGridView1.SelectedRows[0].Index;

Or if you wanted to use LINQ and get the index of all selected rows, you could do:

dataGridView1.SelectedRows.Select(r => r.Index);
Justin Niessner
Helpful (IndexOf was not really "on my radar" yet), but roundabout since getting the row isn't necessary. The .Index method is what I was looking for.
Emtucifor
+1  A: 

Use the Index property in your DGV's SelectedRows collection:

int index = yourDGV.SelectedRows[0].Index;
Jay Riggs
There it is... for some reason I just couldn't find the Index property. Easy money for you!
Emtucifor
Do you think this is better or DGV.CurrentCell.RowIndex?
Emtucifor
+2  A: 

There is the RowIndex property for the CurrentCell property for the DataGridView.

datagridview.CurrentCell.RowIndex

Handle the SelectionChanged event and find the index of the selected row as above.

fletcher
Perfect. This seems simplest/fastest, even over SelectedRows[0].Index. Would that be a good assumption?
Emtucifor
Hmm, I didn't think about multiple rows being selected. I'm not sure of the behaviour of current cell in this case.
fletcher
If it's anything like Excel, the selected list can be many rows/columns, but there is only one current/active cell. I only care about the current row so this should do fine.
Emtucifor
+1  A: 

Try DataGridView.CurrentCellAddress.

Returns: A Point that represents the row and column indexes of the currently active cell.

E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )

Kilanash
That returns a Point data type with properties X and Y which return pixel position... I need the row number.
Emtucifor
Erm, my apologies. I misspoke in my ignorance. So advise me, which is better: DGV.CurrentCellAddress.Y or DGV.CurrentCell.RowIndex?
Emtucifor
P.S. since I asked for the row index, things would have been less rocky in our relationship if you'd said `DataGridView.CurrentCellAddress.Y` ... :)
Emtucifor
I think at this point all of these answers are valid, it's just up to you which one you want to choose that's cleanest for your purposes. I'd suggest typing up the different implementations and looking at the IL in .NET Reflector (http://www.red-gate.com/products/reflector/) if you really want to see what code gets generated for each, but as many will say, that's micro-optimization. It's really down to what's most clear in intent. PS Note taken to be more clear in future.
Kilanash