ListItem ?

callbooks

New member
Joined
Oct 23, 2008
Messages
4
Programming Experience
Beginner
Hello Everyone,

Just signed up to this forum out of desperate need for help. :)

I need a ListItem that stores Text and Value separately. The ListBox and ComboBox would only store an Item, but it cannot store a separate Value. I need to store a string(text) and an id number(value), so ListItem would do the job. But it's not available on VB.NET. Or is it?

Please advice on how I can store these two in VB.NET. Thank you so much in advance. :) :)
 
Add custom object to the ListBox, Override tostring?

VB.NET:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim myValue As Object = New Object
        ComboBox1.Items.Add(New ValueAndText(myValue, "This will be diplayed!"))
    End Sub
End Class

Public Class ValueAndText

    Private _value As Object
    Private _text As String

    Sub New(ByVal value As Object, ByVal text As String)
        _value = value
        _text = text
    End Sub
    Public Property Value() As Object
        Get
            Return _value
        End Get
        Set(ByVal value As Object)
            _value = value
        End Set
    End Property

    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property

    Public Overrides Function ToString() As String
        Return _text
    End Function

End Class
 
Thank you so much Rocksteady!

I just have one last question. How can use that on a ListBox? Can I also save a separate text and value on it? Thanks a lot. :)
 
ListBox1.Items.Add(New ValueAndText(myValue, "This will be diplayed!"))

I just created the ValueAndText class and wrote some code:

VB.NET:
 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ListBox1.Items.Add(New ValueAndText(101, "TESTING"))
        ListBox1.Items.Add(New ValueAndText(102, "TRIAL"))
        ListBox1.Items.Add(New ValueAndText(103, "EXERCISE"))
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = "SELECTED ITEM: " + ListBox1.SelectedItem + "\nSELECTED VALUE: " + ListBox1.SelectedValue
    End Sub

When I click Button1, it says:

"Additional information: Operator is not valid for string "SELECTED ITEM: " and type 'ValueAndText'."

How can I access the text and the value separately? Thanks..

(I hope you're not annoyed by my questions..)
 
Don't use SelectedValue, that's more for databinding.

VB.NET:
Ctype(ListBox1.SelectedItem,ValueAndText).Value
Ctype(ListBox1.SelectedItem,ValueAndText).Text
 
Back
Top