How to retrieve selected values for selected items in a ListBox?

后端 未结 3 982
傲寒
傲寒 2021-01-25 07:23

I\'m populating a ListBox in a WinForms application, this way:

listBoxUsers.DataSource = ctx.Users.ToList();
listBoxUsers.DisplayMember = \"Name\";
listBoxUsers.         


        
相关标签:
3条回答
  • 2021-01-25 08:04

    Have you tried with the SelectedItems property?

    foreach (var item in listBoxUsers.SelectedItems)
    

    {

    }

    0 讨论(0)
  • 2021-01-25 08:06

    Since you know the type of items, you can use such code:

    var selectedValues = listBox1.SelectedItems.Cast<User>().Select(x=>x.Id).ToList();
    

    Side Note: The ListBox control lacks a GetItemValue method. A method which should work like GetItemText, but for getting values. In the linked post I shared an extension method to get the value from an item. Using that extension method you can get selected values independent from type of items:

    var selectedValues = listBox1.SelectedItems.Cast<object>()
                                 .Select(x => listBox1.GetItemValue(x)).ToList();
    

    If for some reason you are interested to have a text representation for selected values:

    var txt = string.Join(",", selectedValues);
    
    0 讨论(0)
  • 2021-01-25 08:12

    try this:

    foreach (DataRowView item in listBoxUsers.SelectedItems)
                {
                  int id=int.parse(item[0].ToString());
                }
    
    0 讨论(0)
提交回复
热议问题