Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleBuild a form from scratch and handle events raised by its controls in Visual Basic .NET
DescriptionThis example shows how to build a form from scratch and handle events raised by its controls in Visual Basic .NET.
Keywordsform, build form, event, AddHandler, Visual Basic .NET, VB.NET
CategoriesControls, VB.NET, Software Engineering
 
When you click the Make Form button, the program creates a new form and sets its size and caption.

The program then creates a button and sdets its properties. It uses AddHandler to make the main form's btn_Click event handler catch the button's Click event. Finally it adds the button to the form's Controls collection to add the button to the form.

 
' Make the new form.
Private Sub btnMakeForm_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnMakeForm.Click
    Dim frm As New Form
    frm.Size = New Size(300, 200)
    frm.Text = "New Form"

    Dim btn As New Button
    btn.Text = "Click Me"
    btn.Size = New Size(100, 30)
    btn.Location = New Point( _
        (frm.ClientSize.Width - btn.Width) / 2, _
        (frm.ClientSize.Height - btn.Height) / 2)
    AddHandler btn.Click, AddressOf btn_Click
    frm.Controls.Add(btn)

    frm.Show()
End Sub
 
The btn_Click event handler converts the sender parameter into the button that raised the Click event. It uses that button's FindForm method to get the button's form. It then closes that form.
 
' Respond to the new form's button click.
Private Sub btn_Click(ByVal sender As System.Object, ByVal _
    e As System.EventArgs)
    Dim btn As Button = DirectCast(sender, Button)
    Dim frm As Form = btn.FindForm
    frm.Close()
End Sub
 
Note that building a form from scratch probably won't save the application much memory or anything. It's usually better to simply build the form at design time and create an instance of it at run time. However, if you really need to, you can use these techniques to build a form that might have different controls depending on the situation.

Also note that you can read the code that Visual Basic writes to build a form and use some or all of that code to do the same yourself.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated