How do you properly use the GetRowCount Method with multiple runtime generated datagridview controls?

StackOverflow https://stackoverflow.com/questions/13765169

Question

I have multiple runtime generated datagridview controls and I would like to be able to see if the user has selected multiple rows in a specific datagridview. For some reason, the result of the following is always zero. When I F9 stop the program, I can see that the selected value of this datagridview row is false. Any ideas how to fix this?

My code is as follows:

strDGVName = "dgvCheckpoint" & intTimeModificationSender

For Each tbp As TabPage In frmTimingP2P.tabctrlTimingTable.Controls
    For Each dgv In tbp.Controls
        If dgv.Name = strDGVName Then
            intSelectedRowCount = dgv.Rows.GetRowCount(DataGridViewElementStates.Selected)
        End If
    Next
Next

Thanks

I have now tried the following:

For Each tbp As TabPage In frmTimingP2P.tabctrlTimingTable.Controls
    For Each ctrl As Control In tbp.Controls
        Dim dgv As DataGridView = TryCast(ctrl, DataGridView)
        If Not dgv Is Nothing Then
            If dgv.Name = strDGVName Then
                intSelectedRowCount = dgv.SelectedRows.Count
            End If
        End If
    Next
Next

As well as:

Dim c As Collections.Generic.IEnumerable(Of DataGridView)
For p = 0 To frmTimingP2P.tabctrlTimingTable.TabCount - 1
    c = frmTimingP2P.tabctrlTimingTable.TabPages(p).Controls.OfType(Of DataGridView)()
    If c(0).Name = strDGVName Then p = frmTimingP2P.tabctrlTimingTable.TabCount
    End If
Next
intSelectedRowCount = c(0).SelectedRows.Count

But it still returns a zero row count.

Was it helpful?

Solution 2

Ok, so the solution is as follows:

Both:

For Each tbp As TabPage In frmTimingP2P.tabctrlTimingTable.Controls
    For Each ctrl As Control In tbp.Controls
        Dim dgv As DataGridView = TryCast(ctrl, DataGridView)
        If Not dgv Is Nothing Then
            If dgv.Name = strDGVName Then
                intSelectedRowCount = dgv.SelectedRows.Count
            End If
        End If
    Next
Next

And:

Dim c As Collections.Generic.IEnumerable(Of DataGridView)
For p = 0 To frmTimingP2P.tabctrlTimingTable.TabCount - 1
    c = frmTimingP2P.tabctrlTimingTable.TabPages(p).Controls.OfType(Of DataGridView)()
    If c(0).Name = strDGVName Then p = frmTimingP2P.tabctrlTimingTable.TabCount
Next
intSelectedRowCount = c(0).SelectedRows.Count

Work as they should. The problem was that in my runtime generated DataGridView controls, I did not set the SelectionMode Method to FullRowSelect, and I was selecting individual cells, which do not count as "Rows".

Thanks for your help!

OTHER TIPS

This should be what you are looking for:

dgv.SelectedRows.Count
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top