NickSharp
NickSharp

Reputation: 281

Count the number of selected rows in a DataGridView

How to count the number of selected rows in a DataGridView?

Let's say I highlighted 5 rows, how can I show it in message box?

Please help I'm using WinForms in C#!

Upvotes: 4

Views: 27684

Answers (3)

Kim Crosser
Kim Crosser

Reputation: 433

If your DataGridView allows Cell Select, you cannot directly get the count of rows selected. Instead, you must iterate through the SelectedCells collection to count the number of distinct selected rows. Here is a function that will return the count of currently selected rows based on the selected cells.

    public int DataGridViewRowCount(DataGridView dgv)
    {
        Dictionary<int, int> RowsFound = new Dictionary<int, int>();
        int nCells = dgv.GetCellCount(DataGridViewElementStates.Selected);
        int nRows = 0;
        if (dgv.AreAllCellsSelected(true))
            nRows = dgv.Rows.Count;
        else
        {
            for (int i = 0; i < nCells; i++)
            {
                int rix = dgv.SelectedCells[i].RowIndex;
                if (!RowsFound.ContainsKey(rix))
                    RowsFound.Add(rix, rix);
            }
            nRows = RowsFound.Count;
        }
        return nRows;
    }

Note that for large numbers of rows (and thus large numbers of Selected Cells), the AreAllCellsSelected function will let you avoid the iteration and just return the number of Rows in the grid. The argument to AreAllCellsSelected is a boolean whether to include invisible cells or not.

A Dictionary is used rather than a List to take advantage of the key indexing and performance when dealing with large numbers of selected cells.

Upvotes: 0

cyberponk
cyberponk

Reputation: 1766

In VB.NET you can use a Lambda expression. Should be easy to translate to C:

SelectedRowCount = DataGridView1.SelectedCells.OfType(Of DataGridViewCell)().Select(Function(x) x.RowIndex).Distinct().Count()

Upvotes: 0

Ravi Gadag
Ravi Gadag

Reputation: 15881

you need to set YourGridView.MultiSelect=true; MultiSelect When the MultiSelect property is set to true, multiple elements (cells, rows, or columns) can be selected in the DataGridView control. To select multiple elements, the user can hold down the CTRL key while clicking the elements to select. Consecutive elements can be selected by clicking the first element to select and then, while holding down the SHIFT key, clicking the last element to select.

then you can use SelectRows.Count property SelectedRows

MessageBox.Show(yourDataGridView.SelectedRows.Count.ToString());

Upvotes: 9

Related Questions