is there a way to do this

G

Guest

hey all,

i'm using a listbox in my win form and was wondering if i can load an item
to my listbox giving it a name/value pair (like dropdownlist) because i
noticed that the available properties shows a Seletected Value and Selected
Item. What would the syntax look like if this is possible?

thanks,
rodchar
 
C

Claes Bergefall

Those properties are used when binding it to a datasource
In your case it's probably easier to build a small class that holds all the
data that you need, add a (overridden) ToString method and add instances of
that class to your listbox. The item collection is not limited to strings,
you can put anything in there. The listbox will call the ToString method of
the object to determine the string to display. Example:

Public Class MyItem
Public Name As String
Public Value As Integer
Public Sub New(name As String, value As Integer)
Me.Name = name
Me.Value = value
End Sub
Public Overrides Function ToString() As String
Return Me.Name
End Function
End Class
....
myListBox.Items.Add(New MyItem(name1, value1))
myListBox.Items.Add(New MyItem(name2, value3))
myListBox.Items.Add(New MyItem(name3, value3))
....
Dim item As MyItem
item = CType(myListBox.SelectedItem, MyItem)

/claes
 
C

Chris Dunaway

And if you bind the list box to a BindingList(Of MyItem) then it will
automatically updated as you add/removed items from the list. That
way you can keep your data model separate from the UI.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top