How to count the number of selected rows in datagridview vb.net

13,431

Solution 1

On your DataGridView, set the .SelectionMode property to FullRowSelect, then use the .SelectedRows.Count property.

Solution 2

I am having no problem using

Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
    Label1.Text = DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
End Sub

Could it be you're only selecting the cells themselves and not the row selector on the left side? When I select multiple cells I get 0 but using the button that selects an entire row counts correctly.

Share:
13,431
CreoGuy
Author by

CreoGuy

Updated on June 04, 2022

Comments

  • CreoGuy
    CreoGuy almost 2 years

    I'm a complete rookie. I learned so much from here but this one I can't find the answer to. I'm using Visual Studio Pro 2015.

    I found this question, but the answer does not work for my application:

    VB.Net - Is there any way to count the number of selected rows in a datagridview?

    I have a windows form application that has a single column datagridview that is populated by reading a textfile, line by line at runtime.

    I need to display (in a label) the number of rows that the user selects in the datagridview control.

    I have this:

        Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
            Dim selectedRowCount As Integer
            selectedRowCount = DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
            lblNumSelected.Text = selectedRowCount.ToString()
        End Sub
    

    Or this:

        Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
            lblNumSelected.Text = DataGridView1.SelectedRows.Count().ToString()
        End Sub
    

    Both of these methods return 0 (zero) no matter how many rows are selected. Thank you for helping me.

  • CreoGuy
    CreoGuy over 8 years
    You are correct, this was the issue. I have the row selector hidden because I have only one column and the list is not editable by the user.
  • CreoGuy
    CreoGuy over 8 years
    Thank you very much. I learned the lesson, to check every property of the control for clues.