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

这一生的挚爱 提交于 2019-12-20 04:28:08

问题


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

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

how to retrieve the selected Ids when I'm setting the SelectionMode to MultiSimple I want to do a foreach loop on them, like this:

foreach(var itemId in listBoxUsers.SelectedValues)//unfortunately not exist
{
    int id = int.Parse(itemId);
    // . . . 
}

回答1:


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);



回答2:


Have you tried with the SelectedItems property?

foreach (var item in listBoxUsers.SelectedItems)

{

}




回答3:


try this:

foreach (DataRowView item in listBoxUsers.SelectedItems)
            {
              int id=int.parse(item[0].ToString());
            }


来源:https://stackoverflow.com/questions/40819000/how-to-retrieve-selected-values-for-selected-items-in-a-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!