简体   繁体   中英

Get value from listbox item

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?

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

在stackoverflow上回答的问题: 获取匿名类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM