Databinding in Windows Forms
This article is pretty extensive with examples and links to more information. Here is a sample to address a common issue:
“Binding to a ComboBox or ListBox. This sample demonstrates binding data to a ComboBox. Binding data to a ListBox follows the same model.
To bind data to the list of items that are displayed, set the DataSource and DisplayMember properties of the ComboBox. The DisplayMember property is used to determine which property of the State object to display in the ComboBox. For example, the following code binds a ComboBox to an array of State objects.
Public Structure State Private m_shortName, m_longName As StringPublic Sub New(ByVal longName As String, ByVal shortName As String) Me.m_shortName = shortName
Me.m_longName = longName
End Sub
Public ReadOnly Property ShortName() As String
Get Return m_shortName
End Get End Property
Public ReadOnly Property LongName() As String Get
Return m_longName End Get
End Property
End Structure
Private States() As State = {New State("Alabama", "AL"), ..., New State("Wyoming", "WY")}
comboBoxState.DataSource=States
comboBoxState.DisplayMember="LongName"
Typically, in a data-bound form, a ComboBox is used to look up up a value. In this example, the form displays a Customer object. Each Customer object has a Region property that contains a state’s abbreviated name. You want to display a list of full state names that the user can select from. When the user selects a particular state, you want the Customer region to be updated with the state’s abbreviated name, rather than the full name. In order to achieve this, you can do the following:
- set the ComboBox up like the previous example
- set the ValueMember property to point to the state abbreviation property on the State object - State.ShortName
- simple-bind SelectedValue to Customer.Region”
You can read the full article from Quickstart.
