下面的代码示例是一个完整的应用程序,它说明在 ListBox 类实现了 ListControl 类的 DataSource、DisplayMember、 ValueMember 和 SelectedValue 等成员后,如何使用这些成员。本示例加载了
Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Collections Public Class USState Private myShortName As String Private myLongName As String Public Sub New(strLongName As String, strShortName As String) Me.myShortName = strShortName Me.myLongName = strLongName End Sub 'New Public ReadOnly Property ShortName() As String Get Return myShortName End Get End Property Public ReadOnly Property LongName() As String Get Return myLongName End Get End Property Public Overrides Function ToString() As String Return Me.ShortName + " - " + Me.LongName End Function 'ToString End Class 'USState Public Class ListBoxSample3 Inherits Form Private ListBox1 As New ListBox() Private textBox1 As New TextBox()_ Shared Sub Main() Application.Run(New ListBoxSample3()) End Sub 'Main Public Sub New() Me.ClientSize = New Size(292, 181) Me.Text = "ListBox Sample3" ListBox1.Location = New Point(24, 16) ListBox1.Name = "ListBox1" ListBox1.Size = New Size(232, 130) textBox1.Location = New Point(24, 160) textBox1.Name = "textBox1" textBox1.Size = New Size(240, 24) Me.Controls.AddRange(New Control() {ListBox1, textBox1}) ' Populates the list box using DataSource. ' DisplayMember is used to display just the long name of each state. Dim USStates As New ArrayList() USStates.Add(New USState("Alabama", "AL")) USStates.Add(New USState("Washington", "WA")) USStates.Add(New USState("West Virginia", "WV")) USStates.Add(New USState("Wisconsin", "WI")) USStates.Add(New USState("Wyoming", "WY")) AddHandler ListBox1.SelectedValueChanged, AddressOf ListBox1_SelectedValueChanged ListBox1.DataSource = USStates ListBox1.DisplayMember = "LongName" ListBox1.ValueMember = "ShortName" End Sub 'New Private Sub InitializeComponent() End Sub 'InitializeComponent Private Sub ListBox1_SelectedValueChanged(sender As Object, e As EventArgs) If ListBox1.SelectedIndex <> - 1 Then textBox1.Text = ListBox1.SelectedValue.ToString() End If End Sub 'ListBox1_SelectedValueChanged End Class 'ListBoxSample3