How to add and remove control to any container control in vb.net

If you want to add any windows form control to container control like Panel,Groupbox etc. or remove control in same manner. Then we can use Controls.Add(obj) and Controls.Remove(obj), on here obj as a parameter any object that derives from the Control class

Example

following example show how to add and remove control to any container control in vb.net. in this example we take Button as control and panel as container control named Panel1

Add Control to container control:

Public NewButton As New Button()
  1.     Public Sub AddNewControl()
  2.         Panel1.Controls.Add(NewButton)
  3.       AddHandler NewButton.Click, AddressOf NewPanelButton_Click
  4.     End Sub

Remove control from container control:

Public Sub RemoveControl()
  1.         If Panel1.Controls.Contains(NewButton) Then
  2.             RemoveHandler NewButton.Click,  _
  3.                AddressOf NewPanelButton_Click
  4.             Panel1.Controls.Remove(NewButton)
  5.             NewButton.Dispose()
  6.         End If
  7.     End Sub

facebooktwittergoogle_plusredditpinterestlinkedinmail