Adding / Deleting Controls at Run Time in VB
Hello all, and welcome to my first official VB Wednesday! *doot-da-doo*
Today, I’ll discuss how to add and remove controls (buttons and picture boxes) on a form during runtime in VB.
Sometimes, though, the need arises to create controls at run time. The most common reason for this would be a login scenario. The user logs in on the sidebar, and extra content shows up on the page.
For purpose of example, I have created a little demo of this method. Though it isn’t a login scenario (I didn’t think of that until I wrote it :P), it should give you a good idea of how to use this technique.
You can download the demo here. For the executable, unzip the file, and go to ButtonGame\bin\Debug and run ButtonGame.exe.
Now, open up the code and look at the source for ButtonGame.vb. On lines 12- 22, you’ll see the following code:
Dim NewButton As New Button() Me.Controls.Add(NewButton) If nBackColor <> Nothing Then NewButton.BackColor = nBackColor End If NewButton.Height = nHeight NewButton.Text = "I'm a button!" NewButton.Width = 115 NewButton.Location = New Point(r.Next(525), r.Next(430))
What happens here? Well, on line 12, we create a button. At this point, the button is just an abstract identity; it’s not actually on the form. Then on line 13, we add it to
Me.Controls. This is a very important variable that stores a list of all controls on a form. You may have seen it used for parsing controls before. Here, we add our button, thus adding it to the form. Pretty nifty, eh?
Now, glance down to lines 42 – 50.
For x = 1 To 100 For Each c As Control In Me.Controls If TypeOf c Is Button Or TypeOf c Is PictureBox Then If Not c.Name.StartsWith("saveme") Then Me.Controls.Remove(c) End If End If Next Next
What happens here is that we parse all of the controls on the form. We then use an If statement to restrict the parsing to only Buttons and PictureBoxes (the bunny button produces these). If the name of the control does not indicate that it should be kept from deletion, we remove it from the form by taking it out of
So, that’s how to add and remove controls from a form during runtime. It may be simple, but it is also helpful.
I’ll see you on Friday! If you have any funny computer-related jokes/pics, then please send them in! Do pobachennya (that’s Ukrainian for good bye)!