Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Windows Forms

Data Binding and Validation

Learn WinForms data binding and validation in VB.NET - BindingSource, DataBindings, INotifyPropertyChanged, BindingList, Validating events and ErrorProvider - with runnable C# stand-ins.

Copying values from a business object into text boxes and back again, by hand, is tedious and error-prone. Data binding lets a control keep itself in sync with a property: change the object, the screen updates; edit the screen, the object updates. Pair it with validation and you have the core of every data-entry form.

This lesson's VB is read-only (no WinForms runtime is available here). The runnable blocks are C# stand-ins: they implement the same INotifyPropertyChanged contract and the same validation rules, with a tiny hand-written "binder" in place of the real Binding class.

Simple binding

Any control property can be bound to a property of an object:

VB
Dim customer As New Customer With {.Name = "Ada", .Credit = 100D}
txtName.DataBindings.Add("Text", customer, "Name")
nudCredit.DataBindings.Add("Value", customer, "Credit")

When the user edits the text box and leaves it, the binding writes the new text into customer.Name. In the other direction, the object must announce changes, or the screen will not know.

INotifyPropertyChanged

A class tells bindings that a property changed by implementing INotifyPropertyChanged and raising PropertyChanged from each setter:

VB
Imports System.ComponentModel
Imports System.Runtime.CompilerServices

Public Class Customer
    Implements INotifyPropertyChanged

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

    Private _name As String
    Public Property Name As String
        Get
            Return _name
        End Get
        Set(value As String)
            If _name = value Then Return
            _name = value
            OnPropertyChanged()
        End Set
    End Property

    Private Sub OnPropertyChanged(<CallerMemberName> Optional prop As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(prop))
    End Sub
End Class

<CallerMemberName> makes the compiler fill in the calling property's name, so you never mistype it.

C# INotifyPropertyChanged with a tiny binder (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.

Binding lists and BindingSource

For collections use BindingList(Of T): it raises ListChanged when items are added or removed, so a bound DataGridView updates immediately. A BindingSource sits between the data and the controls, tracking the current item, sorting, filtering and navigation:

VB
Dim people As New BindingList(Of Customer)
Dim source As New BindingSource With {.DataSource = people}
grid.DataSource = source
txtName.DataBindings.Add("Text", source, "Name")   ' follows the grid's selected row
source.MoveNext()
people.Add(New Customer With {.Name = "Linus"})    ' grid shows it at once
C# BindingList raises ListChanged

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.

Validation

WinForms validation happens when focus leaves a control. The Validating event fires first; set e.Cancel = True to keep focus in the invalid control. ErrorProvider shows a small red icon with a message.

VB
Private Sub txtEmail_Validating(sender As Object, e As CancelEventArgs) Handles txtEmail.Validating
    If Not txtEmail.Text.Contains("@") Then
        errors.SetError(txtEmail, "Enter a valid e-mail address")
        e.Cancel = True
    Else
        errors.SetError(txtEmail, "")
    End If
End Sub

Cancelling Validating can trap users, so many apps skip e.Cancel, show the icon and validate everything again when the user presses Save with ValidateChildren().

Put the rules in the model, not in the handler. Then you can test them without a window and reuse them anywhere:

VB
Public Function Validate() As Dictionary(Of String, String)
    Dim errs As New Dictionary(Of String, String)
    If String.IsNullOrWhiteSpace(Name) Then errs("Name") = "Name is required"
    If Credit < 0 Then errs("Credit") = "Credit cannot be negative"
    Return errs
End Function
C# Model-level validation (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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which interface lets a model tell bound controls that a property changed?

    Raising PropertyChanged from the setter notifies bindings.
  2. 2. Why use BindingList(Of T) instead of List(Of T) for a bound grid?

    List(Of T) raises no change notifications, so the grid would not refresh.
  3. 3. What does e.Cancel = True do in a Validating handler?

    Cancelling Validating prevents focus from leaving the invalid control.
  4. 4. Where should validation rules ideally live?

    Model-level rules can be tested without any UI.

Summary

  • DataBindings.Add links a control property to an object property.
  • Implement INotifyPropertyChanged (use CallerMemberName) so objects can update the screen.
  • BindingList(Of T) and BindingSource handle collections and the current item.
  • Validate with Validating plus ErrorProvider, but keep the rules in the model.

Next: Text Files and Streams