Retrieve info from combobox while adding objects of any type ??

  • Thread starter Thread starter Mendhak
  • Start date Start date
M

Mendhak

Hi All,

When you add an object to a combobox, and run the application, you'll get
something like this:

System.Windows.Forms.Button, Text: Button1

(for example).

Is it possible to have just the text/value in the object to be displayed in
the combobox, yet at the same time when retrieving the combobox item,
getting that same object back?

In this particular case, an object of ANY type can be added to the combobox.

TIA.
 
If I understand you correctly you can you a custom class like so:

add items like this:
cbo.Items.Add(New ListBoxItem(MyObject, "display string"))

retrieve items like this:
Dim MyObject as Object = CType(cbo.SelectedItem, ListBoxItem).Data

Public Class ListBoxItem

Private listItemData As Object
Private listItemText As String

' This is what is displayed in the ComboBox drop-down
Public Overrides Function ToString() As String
Return listItemText
End Function

Public Sub New(ByVal itemData As Object, ByVal itemText As String)

listItemData = itemData
listItemText = itemText
End Sub

Public ReadOnly Property Data() As Object
Get
Data = listItemData
End Get

End Property

Public ReadOnly Property Text() As String
Get
Text = listItemText
End Get

End Property

End Class

HTH,
Greg
 
Mendhak said:
When you add an object to a combobox, and run the application, you'll get
something like this:

System.Windows.Forms.Button, Text: Button1

(for example).


How are you adding objects to the combobox, before running the application?

LFS
 
Mendhak,
As Greg suggests (and his sample shows), unless you are using DataBinding
(you set the ListControl.DisplayMember, ValueMember, & DataSource
properties) a ListControl (ComboBox & ListBox) will use Object.ToString for
the display text.

As you found out Button, overrides Object.ToString to display
"System.Windows.Forms.Button, Text: Button1" when it is called.

Your classes are free to override Object.ToString to return meaningful text.

You can use ComboBox.SelectedItem & ListBox.SelectedItem to return the
actual object that is selected. ListControl.SelectedValue will return the
text (ToString/ValueMember) of the selected item...

Hope this helps
Jay
 
Really appreciate your help on all of this.
Greg's example was what I needed.

Thanks,
Mendhak.
 
Thanks to everyone who responded. I inherited the ComboBox control, and
used Gregg's class.

Some day when I become rich and famous, I'll pay you a trillion dollar
royalty. :D

Thanks,
Mendhak.
 

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

Back
Top