Using a class as ListItem in a ListBox in .Net

Sometimes it could be useful to use classes as listitems in a listbox. This way you can have extra item info directly into the listbox control so when you click on the item you can easily access the full class data. I always use this solution when i work with databases so i don’t need to requery each time i need the data.
The only important thing to do is to provide a ToString() method for your class so when the ListBox draws the items it knows which text to show :)

Here is a simple example:
If you try it, create a listbox and call it “listDoc”

'define a class containing the document info
Public Class CDocument
    Public ID As Long
    Public FileName As String
    Public DocType As String

    Public Sub New(ByVal idf As Long, ByVal FN As String,_
        ByVal DT As String)
        ID = idf
        FileName = FN
        DocType = DT
    End Sub
 
    Public Overrides Function ToString() As String
       Return FileName + " (" + DocType + ")"
    End Function
End Class
 
Public Sub FillDocumentList(ByVal IDMask As Integer)
    Dim i As Integer
    listDoc.Items.Clear()

    For i = 1 To 20
	 listDoc.Items.Add(New CDocument(i.ToString(), _
         "File " + i.ToString() + ".txt", "txt")
    Next
End Sub
 
Private Sub listDoc_SelectedIndexChanged(ByVal sender _
    As System.Object, ByVal e As System.EventArgs) _
    Handles listDoc.SelectedIndexChanged
    Dim d As CDocument
    d = listDoc.SelectedItem

    MessageBox.Show("Document ID : " + d.ID.ToString() + vbCrLf +_
          "Document name : " + d.FileName + vbCrLf +_
          "Doc Type : " + d.DocType + vbCrLf)
End Sub

Download this code: ClassIntoListBox.vb.txt

That’s all, i find this really useful instead of using the Value of ListItem object.



Leave a Reply