Iterate through the items in a Listbox

I have a ListBox (sortedListBox) which I have populated like this by the items in a Combobox (allItemsComboBox):

int index = sortedListBox.FindString(allItemsComboBox.Text, -1);
if (index == -1)
{
    var item=new { Text = allItemsComboBox.Text , Value = allItemsComboBox.Value};
    sortedListBox.Items.Add(item);
}

The DisplayedMember of sortedListBox is "Text" and ValueMember of it is "Value".

Now I want to iterate through all items in the ListBox and get its values:

public static string ListBoxToString(ListBox lb)
{
    List<string> values = new List<string>();            
    for (int i = 0; i < lb.Items.Count; i++)
    {
        values.Add(lb.Items[i].ToString());  
    }

    string result = String.Join(",", values);
    return result;
}

In this line: values.Add(lb.Items[i].ToString()); I get:

{ Text = "Size" , Value = "cte1.Size"}

I just want to have the value , which is "cte1.Size"

How can I iterate through the items in the ListBox and get the ValueMember of these?

Jon Skeet
people
quotationmark

I don't know that there's any way to ask the ListBox to evaluate the ValueMember for you in that way... and because you're using an anonymous type, it becomes harder to get the value.

Options:

  • Use a named type instead, and cast each item to that
  • Use dynamic typing

For example:

public static string ListBoxToString(ListBox lb)
{
    var values = lb.Items
                   .Cast<dynamic>()
                   .Select(x => x.Value.ToString());
    return string.Join(",", values);
}

Dynamic typing provides the most immediate fix, but I'd strongly encourage you to consider using a custom type. (It needn't take more than a few lines to write.)

people

See more on this question at Stackoverflow