Add controls on the fly

February 4, 2009 on 1:24 pm | In Programming | 4 Comments

To add controls to your form (for example if a condition is met)

Dim RadioButton4 As New RadioButton()
Dim Label12 As New Label
RadioButton4.Text = “option 2”
RadioButton4.Appearance = Appearance.Button
RadioButton4.FlatAppearance.CheckedBackColor = Color.BlueViolet
If choice = “option 2” Then
RadioButton4.Checked = True
End If
RadioButton4.Location = New Point(287, 114)
RadioButton4.Size = New Size(95, 23)
Me.Controls.Add(RadioButton4)

Label12.Text = “explanation of choices”
Label12.Location = New Point(287, 16)
Label12.Size = New Size(95, 13)
Label12.Font = New Font(label12.Font, FontStyle.Bold)
Me.Controls.Add(Label12)

4 Comments »

RSS feed for comments on this post. TrackBack URI

  1. Note that if you want to add for example a Click Event to a button that gets added later you need to add a line to the Form.Designer.vb similar to his one:
    Friend WithEvents Button6 As System.Windows.Forms.Button

    If you don’t you will get an error:
    Handles clause requires a WithEvents variable defined in the containing type or one of its base types.

    Comment by Pieter — February 27, 2009 #

  2. Hello 🙂

    You can manually add functions to the event handlers instead of using “Handles” if you don’t want to have to declare a friend or local variable inside the form.

    Syntax is “AddHandler Event,Addressof function”
    For example:
    Dim btn as new Button
    Function iGotClicked(ByVal sender As Object, ByVal e As System.EventArgs)
    MsgBox(“This is some code run because I got clicked!”)
    End Function
    AddHandler btn.Click, AddressOf iGotClicked
    Form.Controls.Add(btn)

    Billy3

    Comment by Billy O'Neal — March 11, 2009 #

  3. Thank you 😀

    Comment by Pieter — March 11, 2009 #

  4. […] View full post on Metallica’s blog […]

    Pingback by Add controls on the fly | Computer Security Articles — May 4, 2010 #

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Powered by WordPress with Pool theme design by Borja Fernandez.
Entries and comments feeds. Valid XHTML and CSS. ^Top^