0

I'm trying to get just the value from all items in a listbox using c# (winforms). I have a combobox with multiple items, this are filled from datasource and whem I commit a selection in the combo I want this values to be stored in the listbox.

IQueryable clientes = getcompanies();
combo1.DataSource = companies;
combo1.DisplayMember = "name";
combo1.ValueMember = "id";

 private void combo1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        listBox1.Items.Add(combo1.SelectedItem);
        listBox1.DisplayMember = "name";
        listBox1.ValueMember = "id";
    }
public IQueryable getcompanies()
    {
        var company= from c in context.companies
                       select new
                       {
                           c.id,
                           name= c.fname+" "+ c.lname
                       };
        return company;
    }

I have no problems with this code, when I select and item from the combo it is added to the listbox and only the displaymember property is visible, just as I wanted. The problem is that I don't know how to get all valuemember properties from all items in the listbox. Any ideas?

Jorge Zapata
  • 2,316
  • 1
  • 30
  • 57

2 Answers2

2

if you do this.

var items = ((List<string>)listBox1.Items);

you ill need to change List to the data type of companies

You should then be able to loop though items using a foreach loop, which you can then access the propertie id as normal

Jonathan D
  • 1,364
  • 2
  • 12
  • 30
  • Thanks Jonathan, companies is a IQueryable data type and I get a conversion error (ObjectCollection' to 'System.Linq.IQueryable') – Jorge Zapata Sep 28 '11 at 23:06
  • without more code i cant help much, basicly you have the wrong type where i said replace List. step though the code in deubg mode and see what listBox1.Items is and cast it to that. – Jonathan D Sep 28 '11 at 23:20
  • I added more details in the question. Listbox.items is ObjectCollection data type. – Jorge Zapata Sep 28 '11 at 23:27
1

Question answered here on stackoverflow: Get back anonymous type

Community
  • 1
  • 1
Jorge Zapata
  • 2,316
  • 1
  • 30
  • 57