Search code examples
c#visual-studio-2010listboxvaluemember

How to get the ValueMember of an item in a Listbox for a given index number?


I have a ListBox which holds aDisplayMember called "Data" and a ValueMember called "Number". I want to get the ValueMember of all the items using a loop as following.

for (int i = 0; i < ListBox1.Items.Count; i++)
{ 
    //Get the `ValueMember` of `Item` where it's `Index` is `i` 
}

Solution

  • Did you tried like code below:

    for (int i = 0; i < ListBox1.Items.Count; i++)
    { 
       Console.WriteLine((ListBox1.Items[i] as YourItemClassType).Number.ToString());
    }
    

    YourItemClassType is your class that you adding to ListBox1, YourItemClassType contains Number and Data properies

    Hope helps