Wednesday, July 11, 2007

Get the current selected row in VB.NET DataGridView

Something that gets asked often in the forums is:
'How do I get a hold of the currently selected row in a datagridview?' so that I can pick a particular cell and manipulate it, use it for a calculation etc.

The trick is knowing that DataGridView1.CurrentCell will tell you the cell the user chose.
So if we ask for the Rowindex like this:

Then we can combine it with the Datagridviews rows collection to index just that row, like this:

We can take this further to drill into a column in that row by accessing the rows cells property like this:
DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells().Value += 1

No comments: