如何检索列表框中选定项目的选定值? [英] How to retrieve selected values for selected items in a ListBox?

查看:73
本文介绍了如何检索列表框中选定项目的选定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用以下方式在WinForms应用程序中填充一个列表框:

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

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

在将SelectionMode设置为MultiSimple时如何检索选定的ID 我想对它们执行foreach循环,如下所示:

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);
    // . . . 
}

推荐答案

由于您知道项目的类型,因此可以使用以下代码:

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

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


侧面说明:ListBox控件缺少 GetItemValue 方法.该方法应类似于GetItemText,但用于获取值.在链接的帖子中,我共享了一种扩展方法,可从项目中获取价值.使用该扩展方法,您可以获得与项目类型无关的所选值:


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

这篇关于如何检索列表框中选定项目的选定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆