Matt Porterfield
Matt Porterfield

Reputation: 123

Why does ListBox not display objects correctly?

I have a listbox and a class. The class is called CTS_Warnings_List And the listbox is called lbpropWarningFacList

Here is the class:

Public Class CTS_Warnings_List
Public _Warning As String
Public _WarnID As Integer


Public Property Warning() As String
    Get
        Return _Warning
    End Get
    Set(ByVal value As String)
        _Warning = value
    End Set
End Property

Public Property WarnID() As Integer
    Get
        Return _WarnID
    End Get
    Set(ByVal value As Integer)
        _WarnID = value
    End Set
End Property


Sub New(ByVal Warning As String, ByVal WarnID As Integer)
    Me.Warning = Warning
    Me.WarnID = WarnID
End Sub

End Class

So now I want to add a new item to the listbox. So I tried this:

Dim llist As New CTS_Warnings_List("K", 8)
    lbpropWarningFacList.Items.Add(llist)

I also tried this:

lbpropWarningFacList.Items.Add(New CTS_Warnings_List("K", 8))

When I run the app and add these to the listbox, in each case I get this displayed in the listbox:

NameOfApplication.NameOfClass

as the display in the listbox.

What am I doing wrong?

Thank you

Upvotes: 0

Views: 107

Answers (3)

Matt Porterfield
Matt Porterfield

Reputation: 123

Thanks for the responses. But I found that if I add

NameOfListBox.DisplayMemeber = "PropertyOfClass"
NameOfListBox.ValueMember = "PropertyOfClass"

By just adding this it now shows the correct data in the listbox.

Upvotes: 1

Zohar Peled
Zohar Peled

Reputation: 82474

Listboxes only knows how to display strings.
Therefor, when you add an item of any type to the listbox, it displays the value it gets by calling the items ToString() method.

You should override the ToString() method or simply enter items as strings in the first place.

In your case, add this to your class:

Public overrides function ToString() as string
    return Me.Warning & " " & Me.WarnID.ToString()
End Function

Upvotes: 3

Tony Hinkle
Tony Hinkle

Reputation: 4742

You are sending a CTS_Warnings_List object to a listbox. How does the listbox know what to do with that object? It doesn't know what to do with that object. If you want to send the properties of the object to the listbox, then you have to do something like:

lbpropWarningFacList.Items.Add(llist._WarnID & ": " & llist.Warning)

Upvotes: 2

Related Questions