Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Windows Forms

Controls and Events

Learn VB.NET WinForms controls and events - Button, TextBox, ListBox, CheckBox, Handles, WithEvents, AddHandler, sender and EventArgs - with read-only VB and runnable C# event stand-ins.

A form is a container; its controls are the things people touch: buttons, text boxes, lists, check boxes, pickers. Each control is a class with properties (what it looks like), methods (what it can do) and events (what happened to it). Connecting your code to events is the heart of WinForms programming, and VB.NET has two distinct ways to do it.

Windows Forms cannot run on this site. VB code is read-only; runnable blocks are C# stand-ins that reproduce the event mechanics with ordinary classes.

The controls you will use daily

Control Purpose Key members
Label Static text Text
Button Trigger an action Text, Click, Enabled
TextBox Edit text Text, TextChanged, MaxLength, Multiline, PasswordChar
CheckBox / RadioButton On/off and exclusive choices Checked, CheckedChanged
ComboBox / ListBox Choose from items Items, SelectedItem, SelectedIndex, SelectedIndexChanged
NumericUpDown Number picker Value, Minimum, Maximum
DateTimePicker Date/time Value
DataGridView Tables DataSource, Rows, CellClick
Timer Periodic event Interval, Tick, Start()

Every control inherits from Control, so they all share Name, Text, Location, Size, Visible, Enabled, Font, BackColor, Focus() and a long list of events.

Handling an event: the Handles clause

VB's classic style is to declare the control WithEvents (the designer does this) and attach a handler with Handles:

VB
Public Class MainForm
    Private Sub btnGreet_Click(sender As Object, e As EventArgs) Handles btnGreet.Click
        lblResult.Text = "Hello, " & txtName.Text & "!"
    End Sub

    Private Sub txtName_TextChanged(sender As Object, e As EventArgs) Handles txtName.TextChanged
        btnGreet.Enabled = txtName.Text.Trim().Length > 0
    End Sub
End Class

One handler can serve several events or controls: Handles btnA.Click, btnB.Click. Inside it, sender identifies who raised the event.

Handling an event: AddHandler

AddHandler attaches a handler at run time, which is the only option for controls you create in code, and it can be undone with RemoveHandler.

VB
Dim b As New Button() With {.Text = "Dynamic"}
AddHandler b.Click, AddressOf OnAnyClick
Me.Controls.Add(b)
...
RemoveHandler b.Click, AddressOf OnAnyClick

Private Sub OnAnyClick(sender As Object, e As EventArgs)
    Dim clicked = DirectCast(sender, Button)
    MessageBox.Show("You clicked " & clicked.Text)
End Sub

Forgetting RemoveHandler on a long-lived object that outlives the subscriber is a classic memory leak: the publisher keeps the subscriber alive through the delegate.

What events really are

A .NET event is a list of delegates (function pointers) that the publisher calls when something happens. The standard shape is Sub(sender As Object, e As EventArgs). The next block builds a tiny control to show exactly what Handles and AddHandler do, including one handler for several controls.

C# Events, sender and EventArgs (C# stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Events with data

Events that need to report details use a subclass of EventArgs: MouseEventArgs (position, button), KeyEventArgs (which key), FormClosingEventArgs (Cancel), DataGridViewCellEventArgs (row and column). You can define your own too.

VB
Public Class PriceChangedEventArgs
    Inherits EventArgs
    Public ReadOnly Property OldPrice As Decimal
    Public ReadOnly Property NewPrice As Decimal
    Public Sub New(oldP As Decimal, newP As Decimal)
        OldPrice = oldP : NewPrice = newP
    End Sub
End Class

Public Class Product
    Public Event PriceChanged As EventHandler(Of PriceChangedEventArgs)
    Private _price As Decimal
    Public Property Price As Decimal
        Get
            Return _price
        End Get
        Set(value As Decimal)
            If value = _price Then Return
            Dim old = _price
            _price = value
            RaiseEvent PriceChanged(Me, New PriceChangedEventArgs(old, value))
        End Set
    End Property
End Class
C# A custom event with data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Good habits

  • Name controls with a prefix and meaning: btnSave, txtEmail, lstCustomers.
  • Keep handlers short; call a method that does the real work so it can be tested without a window.
  • Never put long-running work in a handler (see the message loop).
  • Unsubscribe from events of objects that live longer than the form.
  • Use sender instead of hard-coding the control when one handler serves several.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which clause attaches a handler to a WithEvents control at compile time?

    Handles binds a Sub to one or more events of WithEvents variables.
  2. 2. When must you use AddHandler instead of Handles?

    Dynamically created controls have no WithEvents field, so you subscribe in code.
  3. 3. What is the standard signature of a .NET event handler?

    Sender identifies the publisher; e carries event data.
  4. 4. What is a risk of never calling RemoveHandler on a long-lived publisher?

    The publisher's delegate list keeps subscribers reachable.

Summary

  • Controls expose properties, methods and events; all derive from Control.
  • Use Handles for designer-created controls and AddHandler/RemoveHandler for dynamic ones.
  • Handlers take sender and an EventArgs; custom events use EventHandler(Of T) and RaiseEvent.
  • Keep handlers short and unsubscribe from long-lived publishers.

Next: Layout, Dialogs and Menus