1

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?

1
  • can you post the code you are using to create the controls and add them to the parent? Commented Nov 5, 2011 at 4:50

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

After stepping away for a while, I realized that I was only releasing ownership of the controls, not disposing of them. Your solution works and everything is running correctly.
0
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

1 Comment

That's not what actually happens, the Controls collection doesn't have this kind of protection. The code actually removes the even numbered controls only. The code otherwise leaks just as bad.
0

Try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.