Obtaining Selected Records in Microsoft DataGridView
Test and Monitor | Posted February 22, 2007

In my previous post , I explained how to select multiple items (rows, columns or cells) in the DataGridView control. You may then need to perform certain operations over the selected items, for example, determine the selected rows’ indices, obtain data from the selected cells, and so on.

The DataGridView control has special properties and methods that let you easily access the grid selection. You can obtain the selected rows, columns and cells currently selected using the grid’s SelectedRows, SelectedColumns and SelectedCells properties, respectively.

To obtain a particular item by its zero-based index within the returned collection, you can use the Item(Index) property or the get_Item(Index) method. The total number of elements in the collection is specified by the Count property. However, in the case of large selections, using the Count property can significantly slow down the test performance. The MSDN article Best Practices for Scaling the Windows Forms DataGridView Control gives the following tips on working with DataGridView selections:

  • To determine whether all grid cells are selected, use the grid.AreAllCellsSelected(True) method.
  • To check whether all cells currently visible in the grid are selected, use the grid.AreAllCellsSelected(False) method.
  • To determine the total number of selected cells, use the grid.GetCellCount("Selected") method instead of the grid.SelectedCells.Count property.
  • To determine the number of selected rows, use the grid.Rows.GetRowCount("Selected") method instead of the grid.SelectedRows.Count property.
  • To determine the number of selected columns, use the grid.Columns.GetColumnCount("Selected") method instead of the grid.SelectedColumns.Count property.

The sample routine below demonstrates how you can obtain and process the selected rows in the DataGridView control. It posts the selected rows’ indices to the test log. If no grid rows are selected, or all of them are selected, it posts a corresponding message. This sample requires that the grid’s SelectionMode property be set to RowSelect or FullRowSelect.


By submitting this form, you agree to our
Terms of Use and Privacy Policy

Thanks for Subscribing

Keep an eye on your inbox for more great content.

Continue Reading

Add a little SmartBear to your life

Stay on top of your Software game with the latest developer tips, best practices and news, delivered straight to your inbox