简体   繁体   English

Listbox.items[i].Selected 只捕获第一个选定的项目

[英]Listbox.items[i].Selected only captures the first selected item

I'm trying to loop through and all my selected values within a Listbox and add them to a string.我正在尝试遍历列表框中的所有选定值并将它们添加到字符串中。 However when I do the loop below all I get is the first selected item in the Listbox and none of the subsequent selected items.但是,当我执行下面的循环时,我得到的是列表框中的第一个选定项目,而没有任何后续选定项目。 Can anyone see where I'm going wrong?谁能看到我哪里出错了?

I've tried stepping through it and it just doesn't seem to be realising that the items have been selected.我试过逐步完成它,但似乎没有意识到这些项目已被选中。 Maybe .Selected doesn't work as I'm expecting, which is for all items which have been selected to be picked up.也许 .Selected 不能像我期望的那样工作,这适用于所有已选择要提取的项目。

       string selectedItem = "";
            if (impactedServicesData.Items.Count > 0)
            {
                for (int i = 0; i < impactedServicesData.Items.Count; i++)
                {
                    if (impactedServicesData.Items[i].Selected)
                    {
                        if (selectedItem == "")
                        {
                            selectedItem = impactedServicesData.Items[i].Value;
                        }
                        else
                        {
                            selectedItem += "," + impactedServicesData.Items[i].Value;
                        }
                    }
                }
            }

Make sure you have set the SelectionMode correctly to allow multiple item selection.确保您已正确设置SelectionMode以允许选择多个项目。

Then, for a multi-selection ListBox, you can use SelectedItems to get a collection of all the selected items.然后,对于多选 ListBox,您可以使用SelectedItems来获取所有选定项的集合。

Your code could be re-written as:您的代码可以重写为:

string selectedItem = "";
foreach (var s in impactedServicesData.SelectedItems)
{
    if (selectedItem == "")
    {
        selectedItem = s.Value;
    }
    else
    {
        selectedItem += "," + s.Value;
    }
}

Also consider using a StringBuilder when concatenating many strings in a loop.在循环中连接多个字符串时,还可以考虑使用StringBuilder

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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