List(Of Class)(引用类型)比结构(值类型)更灵活。
使用列表(结构):
Dim Clients As New List(Of User)
Structure User
Dim Name As String
Dim ID As Short
Dim Email As String
End Structure
'Add some elements to it
Clients.Add(New User With {.Name = "User1", .ID = 1, .Email = "Email1"})
Clients.Add(New User With {.Name = "User2", .ID = 2, .Email = "Email2"})
Clients.Add(New User With {.Name = "User3", .ID = 3, .Email = "Email3"})
要填写 ComboBox 列表,您可以:
'Fill it with the whole list
ComboBox1.Items.AddRange(Clients.Select(Function(c) c.Name).ToArray)
'Or filter it using a range of values
Dim SublistClient As New List(Of User)
SublistClient.AddRange(Clients.Select(Function(c) c).Where(Function(c) (c.ID > 1 And c.ID < 3)))
ComboBox1.Items.AddRange(SublistClient.Select(Function(c) c.Name).ToArray)
当用户从列表中选择项目时获取项目值:
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Dim SelectedUser As User = Clients(ComboBox1.SelectedIndex)
Console.WriteLine("Name: {0}, ID: {1}, Email: {2}", SelectedUser.Name, SelectedUser.ID, SelectedUser.Email)
End Sub
使用列表(类)
Dim Clients As New List(Of User)
Class User
Public Property Name As String
Public Property ID As Short
Public Property Email As String
End Class
'You can add items to the list in the same way, nothing will change here
Clients.Add(New User With {.Name = "User1", .ID = 1, .Email = "Email1"})
Clients.Add(New User With {.Name = "User2", .ID = 2, .Email = "Email2"})
Clients.Add(New User With {.Name = "User3", .ID = 3, .Email = "Email3"})
现在您可以使用其.DataSource 属性填充您的 ComboBox
'Add the whole List as the ComboBox `.DataSource`
ComboBox1.DataSource = Clients
'Or filter it using a range of values
ComboBox1.DataSource = (Clients.Select(Function(c) c).Where(Function(c) (c.ID > 1 And c.ID < 3))).ToList()
'Or from a specific value up or down
ComboBox1.DataSource = (Clients.Select(Function(c) c).Where(Function(c) c.ID > 1)).ToList()
'This gives you extended options when you have to present your data
'or evaluate the result of a choice
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
'The user choice is evaluated more or less in the same manner
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
Dim SelectedUser As User = CType(ComboBox1.SelectedItem, User)
Console.WriteLine("Name: {0}, ID: {1}, Email: {2}", SelectedUser.Name, SelectedUser.ID, SelectedUser.Email)
End Sub