Question DGV SelectionChanged / Columns.Visible issue

dfenton21

Member
Joined
Apr 26, 2011
Messages
20
Programming Experience
Beginner
My code below exhibits some unwanted behaviour which I can't figure out how to remedy.

It is a sub to load a DGV with a table returned from the PopulateSessionList function.
If a parameter is passed to the sub containing a row index, that row will be selected, otherwise no row will be selected.
Just before calling this sub, I have removed the SelectionChanged handler from the DGV, and I have tested this to ensure it have actually been removed, as shown here

VB.NET:
RemoveHandler dgvSessions.SelectionChanged, AddressOf dgvSessions_SelectionChanged
dgvSessionsLoad(SelectedRow)
All of that worked perfectly. The problem is this - I added the line to hide the first column, but that fires the SelectionChanged event, eventhough I haven't add the handler yet. The first row of the DGV is also selected.

If a comment out the Column(0).Visible line the event does not fire and the first row is not selected.

I would appreciate if someone could explain what is happening here because I can't understand how changing the visible property of a column can cause the SelectionChanged event to fire eventhough I have removed it prior to calling the sub; and why it is causing the first row to be selected.

Thanks.

VB.NET:
Public Sub dgvSessionsLoad(Optional ByVal SelectRow As Integer = -2)


        dgvSessions.DataSource = clsBll.PopulateSessionList
        dgvSessions.Columns(0).Visible = False


        If SelectRow = -2 Then
            dgvSessions.ClearSelection()
        Else
            dgvSessions.CurrentCell = dgvSessions.Rows(SelectRow).Cells(2)
        End If

        AddHandler dgvSessions.SelectionChanged, AddressOf dgvSessions_SelectionChanged

    End Sub
 
I tested what you explained, but was not able to reproduce the problems related to SelectionChanged that you describe.

Just a thought, in your dgvSessionsLoad you have AddHandler for SelectionChanged, but no RemoveHandler, this method also seems like something you call multiple times. You should realize that each time you use AddHandler a new event handler is added, so if you add twice without remove you have at that point a duplicate subscription to that event.
 
Thanks for looking into this for me.

OK, so I removed all AddHandlers and RemoveHandlers. Forgetting about them for a moment, when I remove the Visible=False line, no rows are selected, which is correct because I use the ClearSelection method. However, when I reinsert the Visible=False line, the first row is selected.

This suggests the problem isn't actually with the Handlers, but for some reason the Visible=False line is affecting the ClearSelection method, or vice versa. I've stepped through the code, and it seems OK.

Any further help would be appreciated.
 
Back
Top