# VBForums CodeBank > CodeBank - C# >  Get Value for Items in ComboBox or ListBox as SelectedValue Does for SelectedItem

## jmcilhinney

VB version here.

If you bind a WinForms ComboBox or ListBox to a data source and set the ValueMember, you can use the SelectedValue property to get that property value from the SelectedItem.  Unfortunately, there is no way to do the same for other items.  Obviously it is most important for the item that is selected but there are times when it would be useful to be able to do the same for other items, e.g. a ListBox that allows multiple selections.

The custom controls below inherit the ComboBox and ListBox classes and add a GetItemValue method.  The functionality is based on the ListControl class, which is the base for both ComboBox and ListBox.  As a result, you can do the same for any other class that is also derived from ListControl, e.g. CheckedListBox.

csharp Code:
public class ComboBoxEx : ComboBox{    public object GetItemValue(object item)    {        var index = this.Items.IndexOf(item);         if (index != -1 && this.DataManager != null)            return this.FilterItemOnProperty(this.DataManager.List[index], this.ValueMember);         return null;    }}

csharp Code:
public class ListBoxEx : ListBox{    public object GetItemValue(object item)    {        var index = this.Items.IndexOf(item);         if (index != -1 && this.DataManager != null)            return this.FilterItemOnProperty(this.DataManager.List[index], this.ValueMember);         return null;    }}
The method is written to be consistent with the definition of the existing GetItemText method and the implementation of the existing SelectedValue property.  It will return Nothing if the object provided is not in the control's list and it will return the item itself if the item is valid but the ValueMember is not set.  Here is an example of it's usage, which gets the text and value for each item selected in a ListBoxEx control:

csharp Code:
foreach (var item in listBoxEx1.SelectedItems){    MessageBox.Show(listBoxEx1.GetItemValue(item).ToString(),                    listBoxEx1.GetItemText(item));}
For those who aren't already aware, you can add a new class to your WinForms project, add this code then build you project to have the new control automatically added to the Toolbox, ready to be dragged onto a form.

----------

