GetRowCount question

StewartBW 845 Reputation points
2024-06-20T12:20:47.3666667+00:00

Hello

I just found something here:

https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/selection-modes-in-the-windows-forms-datagridview-control?view=netframeworkdesktop-4.8&source=recommendations

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:

DataGridView.Rows.Count

with:

DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible)

As well as:

DataGridView.SelectedRows.Count

with:

DataGridViewX.Rows.GetRowCount(DataGridViewElementStates.Selected)

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

Thanks :)

C#
C#
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
VB
VB
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
    2024-06-21T06:45:33.0066667+00:00

    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