Title | Use classes to display data in a ListBox in .NET |
Keywords | VB.NET, NET, ListBox, class |
Categories | Controls, VB.NET |
|
|
In VB .NET, a ListBox can display items that are members of a class you build. It uses the class' ToString method to determine what to display for each item. Later you can use the ListBox's SelectedItem method to see which item is selected.
The following code shows a simple FoodItem class. Notice how the ToString method which returns the object's m_Name value.
|
|
' A class to store information
' about food items.
Private Class FoodItem
Private m_Name As String
Private m_Category As String
' Initialize the object.
Public Sub New(ByVal new_name As String, ByVal _
new_Category As String)
m_Name = new_name
m_Category = new_Category
End Sub
' Return the object's name.
Public Overrides Function ToString() As String
Return m_Name
End Function
' Return the object's Category.
Public Function Category() As String
Return m_Category
End Function
End Class
|
|
The following code shows how the main program creates new FoodItem objects and adds them to the ListBox.
|
|
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
e As System.EventArgs) Handles MyBase.Load
' Load the ListBox.
ListBox1.Items.Add(New FoodItem("Banana", "Fruit"))
ListBox1.Items.Add(New FoodItem("Pie", "Dessert"))
ListBox1.Items.Add(New FoodItem("Cookie", "Snack"))
ListBox1.Items.Add(New FoodItem("Apple", "Fruit"))
ListBox1.Items.Add(New FoodItem("Brownie", "Snack"))
ListBox1.Items.Add(New FoodItem("Hot Dog", "Unknown"))
ListBox1.Items.Add(New FoodItem("Ice Cream", "Dessert"))
ListBox1.Items.Add(New FoodItem("Pizza", "Main Dish"))
ListBox1.Sorted = True
End Sub
|
|
Finally, this code shows how the program display information about the item you click.
|
|
' Display the selected item's information.
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
ListBox1.SelectedIndexChanged
Dim food_item As FoodItem = ListBox1.SelectedItem()
lblInfo.Text = food_item.ToString() & " is a " & _
food_item.Category
End Sub
|
|
In VB 6 and earlier versions, you would need to keep a separate collection or array of FoodItem objects and store the index of each item in the ListBox's ItemData property. This is simpler (once you get used to the idea of ToString).
|
|
|
|