JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Adding Controls to Panels in Code

You can add controls to a panel at run time just as you can add controls to a form. When you add controls to a form, you use the form's Controls collection; when you add controls to a panel, you use the panel's Controls collection. Here's an example, AddControlsPanel on the CD-ROM, where I'm creating a panel, giving it a Fixed3D border, and adding a label and text box to the panel-note that you use the Controls collection's Add method to add the new controls to the panel:

Public Class Form1
    Inherits System.Windows.Forms.Form

    'Windows Form Designer generated code
    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Dim Panel1 As New Panel()
        Dim TextBox1 As New TextBox()
        Dim Label1 As New Label()

        Panel1.Location = New Point(60, 20)
        Panel1.Size = New Size(100, 150)
        Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D

        Label1.Location = New Point(16, 16)
        Label1.Text = "Enter text:"
        Label1.Size = New Size(60, 16)
        TextBox1.Location = New Point(16, 32)
        TextBox1.Text = ""
        TextBox1.Size = New Size(60, 20)

        Me.Controls.Add(Panel1)
        Panel1.Controls.Add(Label1)
        Panel1.Controls.Add(TextBox1)
    End Sub
End Class

You can see this example at work in Figure 6.16; when the user clicks the button in this example, the new panel appears with its contained controls.


Figure 6.16: Creating a panel at run time.

Related solution:

Found on page:

Adding and Removing Controls at Run Time

196

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor