Can anyone tell my why the code...

Form1.Controls.Remove(myCustomControl)

...does not remove the control.

Because whenever I remove a control and add it again, it does not Load but rather just changes its visibility from false to true and all the variables are not reloaded.

I tried to use .Dispose() but VB.net tells me that it can't access a disposed object whenever I try to add the control again.

Any better methods?

Dani AI

Generated

Good clarifications from and the quick fix from . Short technical summary and practical options:

Why the Load handler runs only once

  • Removing a control with Controls.Remove simply unparents the instance; it does not destroy it or reset its internal state or handle. The control’s Load/creation sequence already ran for that instance, so re-adding the same object won’t cause Load to fire again. Calling Dispose does free resources, but a disposed instance cannot be reused (hence the "can't access a disposed object" error).

Practical choices (pick one that fits the scenario)

  • Create a fresh instance when a truly "new" control is needed. New the control, set properties, then call Controls.Add. This ensures constructor/Load run for the new object.
  • Reuse the same instance by adding an explicit reinitialization method inside the custom control. Call it before adding, or have the control detect reparenting and reset itself by overriding OnParentChanged or reacting to Visible changes.

Example patterns (VB)

' inside the custom control
Public Sub ResetState()
    ' restore fields and UI to initial values
End Sub

Protected Overrides Sub OnParentChanged(e As EventArgs)
    MyBase.OnParentChanged(e)
    If Parent IsNot Nothing Then ResetState()
End Sub

Extra tips

  • If disposing the old instance, set the variable to Nothing and create a new instance before adding.
  • Watch event subscriptions: if external objects subscribe to the control, detach them to avoid leaks.
  • Put parent-dependent initialization in OnParentChanged (or Load) and general setup in the constructor so behavior is predictable.

This explains why the Load message box shows once and offers safe ways to get the behavior wanted without hitting ObjectDisposedException.

Recommended Answers

All 6 Replies

.Remove does not delete or alter the control, it just takes it off of Form1.
.Dispose removes the control from Form1 and deletes it.
.Add adds the control to Form1 AS IS.

I'm not sure what you mean by "does not load" and what variables are not reloaded. Give me a little more detail on that part and I will try to point you in the right direction.

Can anyone tell my why the code...

Form1.Controls.Remove(myCustomControl)

...does not remove the control.

Because whenever I remove a control and add it again, it does not Load but rather just changes its visibility from false to true and all the variables are not reloaded.

I tried to use .Dispose() but VB.net tells me that it can't access a disposed object whenever I try to add the control again.

Any better methods?

.Remove does not delete or alter the control, it just takes it off of Form1.
.Dispose removes the control from Form1 and deletes it.
.Add adds the control to Form1 AS IS.

I'm not sure what you mean by "does not load" and what variables are not reloaded. Give me a little more detail on that part and I will try to point you in the right direction.

What do mean by "does not load"?
Control Events > Load. Since you told me that .remove does not delete the control, more than enough answer for me.

-----

Whenever I .Add a control after I .Dispose it, I receive a message "can't access a disposed object"

My program deletes a control and adds it again. I don't want to use .Remove because it requires me to manually reload all variables.

I'm not sure from your post if you still have questions. One thing that looks like you may still be confused is the .dispose and .add. .dispose deletes the control from your program and frees the memory. The only way to do the .add is to recreate the control.

If you still have questions, post a little more detail about your program. Are you manually creating and adding controls to your forms or are they controls created via drag and drop using the GUI? Why are you trying to take them off of the form?

What do mean by "does not load"?
Control Events > Load. Since you told me that .remove does not delete the control, more than enough answer for me.

-----

Whenever I .Add a control after I .Dispose it, I receive a message "can't access a disposed object"

My program deletes a control and adds it again. I don't want to use .Remove because it requires me to manually reload all variables.

I am talking about custom controls by the way.

I am asking is how do you remove a control?. Because when I use .Remove it does not restart the variables inside the said control.

My program adds and removes the control during runtime. When I add a custom control using .add it executes the LOAD event of the control, but when I remove a custom control using .remove and adds it again using .add it no longer executes the LOAD event as if the control was just hidden by the .remove.


-----------------------------

This form adds and removes the custom control

Public Class SampleForm
Dim myControl As New CustomControl
Dim added As Boolean = False ' To prevent the program from adding more than one control

  Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        If added = False Then
            With myControl
                .Left = 100
                .Top = 100
                .Visible = True
            End With
            Me.Controls.Add(myControl)
            added = True
        End If
    End Sub

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
        If added = True then
            Me.Controls.Remove(myControl)
            added = False
        End If
    End Sub

End Class

This custom control shows a message box whenever the EVENT LOAD is executed.

Public Class CustomControl

Private Sub CustomControl_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        MsgBox("Loaded")
    End Sub
End Class

Problem: The message box appears only once, during the first add.

You mention something about recreate, how is that exactly?

>The message box appears only once, during the first add.

...
End With
myControl=new CustomControl
Me.Controls.Add(myControl)
added = True

@adatapost - Thanks. Looks like I have to reNew it afterall. But the New must written before the initialization of properties or else null.

@Smith - Thank very much for your time. I learn a lot on .Add/.Remove/.Dispose.

You guys have just save me hundred lines of code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.