I can’t seem to find an easy to use, .net native way to get Comboboxes on .net winforms to display one value and return another based on the selection without creating my own helper class, with the knowledge that winforms is going to display the ToString method on the object that you put in it.
This is how I’m doing it now, very generically. First, create the helper class.
Public Class ListItem Public Value As Object Public DisplayString As String Public Sub New(ByVal NewValue As Object, ByVal NewDisplayString As String) Value = NewValue DisplayString = NewDisplayString End Sub Public Overrides Function ToString() As String Return DisplayString End Function End Class
then, to load the combobox from a collection or whatever.
For Each o as WhateverObject In CollectionIwantToaddItemsFrom li = New ListItem(o.ValueToReturn, o.ValueToDisplay) Me.ComboBox1.Items.Add(li) Next
and finally, to use the object
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged if me.combobox1.selecteditem is nothing then exit sub Dim li As ListItem = me.ComboBox1.SelectedItem Dim o as object = li.value 'do stuff with o. end sub
I’m sure there is something I’m better to use in the framework that I’m over looking. What is it?
This is a bit of a hack, but it means you don’t have to write your own Name-Value pair class – not a big deal (could be there’s something better already in the framework). But what you could do is use the DictionaryEntry class – which is effectively a name value pair. Add the items to a list, then use the DataMember and ValueMember properties on the combobox to bind to the key and value properties of the DictionaryEntry class. Like this:
Just realised you prefer the vb dialect. The below does the same for VB 🙂