Jon
Jon

Reputation: 40032

Checked List Box with data value property for each item?

Does anyone know of a control such as a Checked List Box where each item can have a value against it.

For example you have a list of fruits and in the listbox it displays Apple, Orange & Banana but the values for those items are A, O & B.

Upvotes: 2

Views: 2367

Answers (3)

Cody Gray
Cody Gray

Reputation: 244772

The CheckedListBox control can already do that. Its Items collection accepts any object that derives from System.Objects. The objects are displayed in the list using the value returned from their ToString method.

Therefore, you can create your own custom classes and add them to the CheckedListBox. Make sure that you overload the ToString method to return the string you want to be displayed in the list box. Then, you can add any other methods or properties to the class that you want. When you get a reference to a selected item, you can cast it to your Fruit class and call any method you want.

Upvotes: 3

Kevin Roche
Kevin Roche

Reputation: 377

I think this is default functionality for .Net Listboxes, comboboxes etc.

If your Listbox has a datasource with items which have properties FruitName and FruitId you can set the DisplayMember to FruitName and the ValueMember to FruitId.

On selecting an item the SelectedValue will be the FruitId.

Upvotes: 1

joe_coolish
joe_coolish

Reputation: 7259

What platform? If it is HTML, then the <select /> tag can have a different value and display string.

If you are working with Winforms, you can set the ListBox to have any type of object. so you could make a class that has a string for display and some kind of object for its value. Then override the ToString() method and return the display string and there you go!

Upvotes: -1

Related Questions