I have a class called optionCode:
Class optionCode
Public description As String
Public optCode As String
End Class
I have a query the returns a list of this optionCode class:
Dim _SelectActiveOptionCodes2 = (From _OptCodes In _EntityModel.tblOptionCodes
Where _OptCodes.fdStatus = "A"
Select New optionCode With {.description = _OptCodes.fdDescription,
.optCode = _OptCodes.fdOptionCode}).ToList()
I want to use this list to populate a listbox where the description is the display field and the option code is the value field.
When using:
sortableOptionCodes = _SelectActiveOptionCodes2
sortedOptionCodes = _SelectActiveOptionCodes2
OptionCodeListBox.DataSource = sortedOptionCodes
The listbox populates, but every entry is "OptionCodeSearch.Form1+optionCode"
I can't figure out how to use the .ValueMember and .DisplayMember functions to get the listbox to load the way I want.
Edit: This answer is for the web form control. See Plutonix's answer for the windows form control.
I believe what you are looking for are the
DataTextField
andDataValueField
properties of theListBox
.First,
ValueMember
andDisplayMember
work off properties:Gets or sets the property to use as the actual value for the items in the System.Windows.Forms.ListControl.
So your class should use Properties not Fields (there are conditions where Fields are treated/handled differently than Properties).With such classes, it good idea to override ToString so you can specify the default text to display instead of the Type (
OptionCodeSearch.Form1+optionCode
):ValueMember
is typically a numeric, but otherwise once you have theList(of optionCode)
ValueMember
andDisplayMember
are used to tell theListBox
the Property Names:Not for nothing, but primitives like that can be made into a generic use-almost-anywhere class:
Of T
allows you to define the Value data type when you build it:Your list would then be:
It is a little cumbersome to iterate lists, but VS/Intellisense provide hints:
If you are using one of these a lot in a project, you can subclass it:
Now, the whole
Element(Of String)
part is built into your newoptCode
class, making it easier to type, use and remember.The value of these is that you can use the same class for a collection of Name-Value pairs of string, datetime, integer, decimal etc without coding a new class each time you need something like it.