Mike Lewis
Mike Lewis

Reputation: 1322

Re-Creating Dynamic Controls

I have a VB.Net WinForm Program. I dynamically create panels with controls. Each panel has: 2 Labels 1 DataGridView 1 Button Everything works fine the first time I create the panels. Everything gets created, and everything is functional.

If I have to re-create the form, I get rid of the existing panels (and their controls) with this code:

For P = 0 To Panels.Count - 1
    For Each PControl In Panels(P).controls
        Panels(P).controls.remove(PControl)
    Next
    Me.Controls.Remove(Panels(P))
Next
Panels.Clear()
DataGrids.Clear()
lblCounts.Clear()

Where: Panels, DataGrids, & lblCounts are ArrayLists holding controls

When I re-create the panels, I get the panels and all of their controls except Buttons When I step through the debugger, I see the buttons being removed, and I see them being created, but they don't appear in the panel Any ideas?

Upvotes: 1

Views: 886

Answers (3)

Hogan
Hogan

Reputation: 70538

Try this

 WHILE Panels(P).controls.count > 0
    Panels(P).controls.removeAt(1)

Upvotes: 0

LarsTech
LarsTech

Reputation: 81675

Your question is regarding a button not appearing when you are adding the controls, but you are only showing the removal process, which is flawed.

Make a UserControl that holds your Labels, Grid and Button. Add that to your form. That's what UserControls are for.

Also, when you are done using it, just call:

MyControl.Dispose()

Otherwise, I suspect you are leaking memory. Remove does not destroy the object.

Upvotes: 1

Amegon
Amegon

Reputation: 630

For Each PControl In Panels(P).controls
    Panels(P).controls.remove(PControl)
Next

This part may kick you out of your code. The 'For Each' does not like it when its items change during execution. check it with Breakpoints. if is is really a problem , you could do..

lazy method, by just adding .ToList

For Each PControl In Panels(P).controls.ToList
    Panels(P).controls.remove(PControl)
Next

similar to:

Dim AllControls as New List(Of control)
AllControls.AddRange(Panels(P).controls)
For Each PControl in AllControls
    Panels(P).controls.remove(PControl)
Next

or:

For i as integer = Panels(P).controls.count -1 to 0 step -1
    Dim PControl as control = Panels(P).controls(i)
    PControl.parent.remove(PControl)
Next

Upvotes: 0

Related Questions