05-29-2011, 09:03 AM
I need some help regarding a database with listbox.
The listbox is populated like something from database with 3 fields - ID, Name, Date
ID - Name
1 - John
6 - Doe
When I click one of those items, I want it to show the Date in a textbox.
Could someone help me in getting that information into the textbox please?
I'm using a For statement to populate the ListBox.
Please help me. = )
05-29-2011, 12:54 PM
You could store the various date values in an array while you populate the listbox
and then retrieve the value from array when you click on a item in the listbox.
Where exactly are you getting stuck?
06-01-2011, 07:13 AM
You can add any object to a listbox. What the listbox displays is controlled by the ToString function (which you must override).
So, we can create our own object to add to the listbox.
Public Class MyListItem
' Public variables as properties for concise code
Public ID As Integer
Public Name As String
Public theDate As Date
' Constructor to store all the values we're interested in
Public Sub New(ByVal id As Integer, ByVal name As String, ByVal theDate As Date)
Me.ID = id
Me.Name = name
Me.theDate = theDate
' Here we put how we want the data to be displayed in the listbox.
' Your example shows [ID] - [Name] but you could make it say whatever
' you want.
Public Overrides Function ToString() As String
Return ID.ToString & " - " & Name
So now we can add these to the listbox and get the data back from them whenever we want.
' When the form loads, add three items into the listbox to show
' how you create the objects and add them to the list
' I'm adding days to the current date so that they are different to see it working when you click the listbox.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ListBox1.Items.Add(New MyListItem(1, "Bob", Now))
ListBox1.Items.Add(New MyListItem(2, "Frank", Now.AddDays(1)))
ListBox1.Items.Add(New MyListItem(3, "Jeff", Now.AddDays(2)))
' This shows you how to get your class back out of the listbox. The clicking
' of the listbox item is kinda stupid so I've not done much here, but you can
' see how I'm casting (ctype) the listbox item into my class to get the
' information out. All this does is display the date of the selected object
' when the listbox is clicked. I'm checking that a selected item exists so
' that it doesn't error if there is no selected item when the listbox is
Private Sub ListBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Click
' Get the selected item
If ListBox1.SelectedItem IsNot Nothing Then
I hope that makes sense. You can do this with other list controls (like combobox).