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
2010-08-26 18:18:36
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
2010-08-26 18:22:25
+1
A:
Use the Index property in your DGV's SelectedRows collection:
int index = yourDGV.SelectedRows[0].Index;
Jay Riggs
2010-08-26 18:18:49
+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
2010-08-26 18:19:35
Perfect. This seems simplest/fastest, even over SelectedRows[0].Index. Would that be a good assumption?
Emtucifor
2010-08-26 18:24:56
Hmm, I didn't think about multiple rows being selected. I'm not sure of the behaviour of current cell in this case.
fletcher
2010-08-26 18:27:18
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
2010-08-26 18:34:28
+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
2010-08-26 18:21:39
That returns a Point data type with properties X and Y which return pixel position... I need the row number.
Emtucifor
2010-08-26 18:23:49
Erm, my apologies. I misspoke in my ignorance. So advise me, which is better: DGV.CurrentCellAddress.Y or DGV.CurrentCell.RowIndex?
Emtucifor
2010-08-26 18:57:45
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
2010-08-26 19:13:29
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
2010-08-26 19:35:33