【问题标题】:How can I get an array of all selected items in a ListBox?如何获取 ListBox 中所有选定项目的数组?
【发布时间】:2018-12-21 20:56:05
【问题描述】:

我有一个ListBox,它列出了一个目录中的所有.mp3 文件。该程序允许用户选择其中一些.mp3 文件并轻松编辑 ID3 标签(文件属性 - 如艺术家、专辑、标题等)。但是,我找不到获取所有用户选择的项目的数组的方法,而不仅仅是一个。

我已经看到了如何获得一个选定的项目 (listBox.SelectedValue),但我经常会拥有多个选定的项目,因为我使用 MultiSimple 作为选择模式属性(允许我选择多个项目而不仅仅是一个)。据我所知,没有办法做类似listBox.SelectedValue[2]listBox.Item.IndexOf(2).Selected() 的事情。

string[] selectedItems = new string[allMusicBox.SelectedItems.Count];
// A count of how many items have been added to the selected items array
int addedSelectedItems = 0;
for (int i = 0; i < allMusicBox.Items.Count; i++) {
    if (allMusicBox.Items.IndexOf(i).Selected) {
        selectedItems[addedSelectedItems] = allMusicBox.Items.IndexOf(i).ToString();
        addedSelectedItems++;
    }
}

那里的代码实际上不起作用,但这与我正在寻找的内容一致。我想知道如何检查该项目(在“i”的位置)是否被选中,如果是,则将其添加到“selectedItems”数组中。

【问题讨论】:

  • 获取所有选定项目的文本:allMusicBox.SelectedItems.Cast&lt;Object&gt;().Select(x=&gt;allMusicBox.GetItemText(x)).ToArray()

标签: c# winforms


【解决方案1】:

SelectedItems 属性是所有选定项的集合。您不需要遍历所有项目来查看它们是否被选中,因为您可以使用allMusicBox.SelectedItems

Here is the MS docn

如果您确实需要将集合转换为列表,请查看此 SO 问题/答案Fastest Convert from Collection to List<T>

【讨论】:

    【解决方案2】:

    我认为您需要查看 SelectedItems 属性:

        foreach (var item in listBox1.SelectedItems)
        {
            Console.WriteLine(item);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2011-02-01
      • 2016-04-29
      相关资源
      最近更新 更多