ALERT!
Click here to register with a few steps and explore all our cool stuff we have to offer!
Home
Upgrade
Credits
Help
Search
Awards
Achievements
 4384

[VB.NET] Dynamic Controls

by 1UP - 10-11-2016 - 03:52 PM
#1
What is a dynamic control you ask?
Well a dynamic control is a control that is created whenever you need it there. (No this is not dragging and dropping a control onto the form).

For instance let's say when a user clicks a button, you want to make buttons appear according to what they put in the text box. This is somewhat on how you would do it.

Code:
Dim controlCount As Integer
Dim controlButton() As Button
Dim controlPositionTop As Integer = 19
Dim controlButtonName As String = "Button"
Dim controlNamecounter As Integer = 1

Let me explain this bit first.

control is going to be our accumulator for the control array we are setting up. The control array is declared with controllButton().

controlPositionTop is basically telling it how far down on the form you want this. You could also set a variable for left if you wanted to. When I was writing a program that I needed to do this in, I just needed top.

And controlButtonName is the name of the base name of the control.

ControlnameCounter is basically setting itself to one so when the array goes through and places the controls, each one with have a unique name. (EX: button ,button1 ,button2)

Lets continue on:
Code:
For core = 1 To 5
                controlCount += 1
                ReDim Preserve cpuCoreProgressbar(cpu)
controlButtonName = controlButtonName & controlNamecounter.ToString

This bit of code is setting up the for next loop, as well as setting the name for the control that we are about to make.

Code:
controlButton(controlCount ) = New Button

With controlButton(controlCount )
                    .Name = controlButtonName
                    .Size = New Size(100, 20)
                    .Location = New Point(51, controlPositionTop )
                End With

Now we are setting the array to New button. The with block we are setting the properties of the new button, these aren't all the properties, you can use all of the ones from a button you would drag and drop.

Code:
Me.Controls.Add(controlButton(controlCount ))

This adds the control to the form

And finally the counters and the next:

Code:
cputop += 22
                cpuLabeltop += 20
                cpuLableCount += 1
                controlNamecounter += 1
            Next

            me.Refresh()

Me.refresh isn't always needed. But sometimes if you are putting controls on the form and for whatever reason they dont show up, try using that first.
Reply
#2
This is great, thank you for sharing this with the community. Heart
Are you a guest to this site? Click the image below and sign up today!
[Image: FTYbRmR.gif]
Reply

Users browsing: 2 Guest(s)