GetRowCount question

StewartBW 845 Reputation points


I just found something here:

You can retrieve a collection of the currently selected cells, rows, or columns through the SelectedCells, SelectedRows, and SelectedColumns properties of the DataGridView control. Accessing these properties is inefficient when every cell in the control is selected. To avoid a performance penalty in this case, use the AreAllCellsSelected method first. Additionally, accessing these collections to determine the number of selected cells, rows, or columns can be inefficient. Instead, you should use the GetCellCount, GetRowCount, or GetColumnCount method, passing in the Selected value.

Well, does it mean I have to replace all of my:




As well as:




When I need to get the number of rows and number of selected rows?

Thanks :)

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,616 questions
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,659 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 28,941 Reputation points Microsoft Vendor

    Hi @StewartBW ,

    You should replace DataGridView.SelectedRows.Count with DataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected) when you need to get the number of selected rows, as the GetRowCount method is more efficient for this purpose.

    However, for the total number of rows, you should not replace DataGridView.Rows.Count with DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible). The Rows.Count property already gives you the total number of rows, while GetRowCount(DataGridViewElementStates.Visible) will give you the count of rows that are currently visible.

    Best Regards.

    Jiachen Li

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful