Binding Contols Properties

B i n d i n g C o n t r o l P r o p e r t i e s

By Michael McIntyre

mikemc@getdotnetcode.com

You can use data binding to bind a property of a Windows Forms control to a property of another Windows Forms control property. Through the binding, when the property of the first control is changed the property of the second control is changed.

For example, bind the Text property of a TextBox control to the BackColor property of a Button control, so that when a user enters the name of a color in the TextBox, the BackColor of the Button is changed.

Or, bind the Checked property of a Checkbox control to the Visible property of a Button control so that; 1) when a user checks the CheckBox the Button is visible; 2) when a user unchecks the CheckBox the Button is invisible.

Example: Bind Control Properties

  1. Start a new Visual Studio.Net VB.NET Windows Forms project.

  2. To Form1 add three controls:

Checkbox

Name: ShowCheckBox

Text: Show

TextBox

Name: ColorTextBox

Text: Red

Button

Name: TestButton

Text: Text

  1. Copy the code below and paste it into Form1 just above Form1’s End Class line.

Private WithEvents TestBackColorBinding As Binding

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _

Handles MyBase.Load

 Me.TestButton.DataBindings.Add("Visible", Me.ShowCheckbox, "Checked")

 TestBackColorBinding = New Binding("BackColor", Me.ColorTextBox, "Text")

 Me.TestButton.DataBindings.Add(TestBackColorBinding)

End Sub

Private Sub TestBackColorBinding_Format( _

ByVal sender As Object, _

ByVal e As ConvertEventArgs) _

Handles TestBackColorBinding.Format

Dim aColor As Color = Color.Empty



    Try

        Dim newColor As Color = Color.FromName(e.Value.ToString())

        If newColor.IsKnownColor Then

            aColor = newColor

        End If

    Catch

        MessageBox.Show("Please enter a valid color.")

    End Try

    e.Value = aColor

End Sub

  1. Run the application.

  2. Check the ShowCheckBox.

Result: The TestButton control becomes visible.

  1. Change the ColorTextBox text from Red to Green.

Result: The BackColor of TestButton changes from red to green.

If you have used binding to bind data to Windows Forms controls the code should look familiar. The only real difference is the source of the data used to bind the controls.

This technique can be used to create a very dynamic user interface that requires little or no event handling.

To learn more about Windows Forms data binding visit: Data Binding and Windows Forms