Monday, August 30, 2010

Adding controls dynamically

We almost always put controls on our form during design time. That's what we learned when we first learned VB6 and that's what all of us usually do when writing software applications.
But there is another way to put controls on a form --- during execution time.
Although this technique might not be applicable to you now, it's better to know it just in case you encounter a requirement that requires something like this.

As usual we start off with a blank project and a default form is created for us.
Don't worry about this being "Form2" instead of Form1. It doesn't matter what form you use it on.

Make sure there's nothing on the form (see screenshot below):

Double-click on the form or click the "View Code" on the project window so we can enter the codes needed to create controls dynamically.

Copy the codes shown in the screenshot below:
You can skip writing the comments so it won't be tedious. I just put them there to guide you.

So what the code above means is basically we defined a "with events" textbox control variable.
Then we add it dynamically to the forms control (Controls.Add).
The 1st parameter is the control to be created. In this case it's VB.TextBox
The 2nd parameter is the name you want to give to this control (i.e. MyText)
After adding our textbox to the forms control, it's not automatically visible so we have to tell VB to show it (mtxtDynamic.Visible = True)
And lastly just to prove that it is our dynamically added textbox, we just display it's name using MsgBox.

Run the project and you should see a message similar below:

A. This is the default project name (Project1)
B. This is the name of the textbox we created

And when you click the "OK" button, the form will be shown with our textbox.
If you want to move it somewhere else, just set the Left and Top of it, set the width and height to set a different size, etc.

Now we'll trap or handle one of the textboxs events : Change. You can choose any event you want but for this lesson, I'll just use this.

Enter the code similar to the screenshot below:

When you run the project, type something to the textbox we created. The form title or caption would reflect whatever you type in it. (see below):

Well that's it for now. Next time, I'll show you how to create dynamic user-controls. Yes, the one you create and not those built-in controls.

No comments:

Post a Comment