首页 > 解决方案 > C# 查找 ListBox 中所有项目的选定状态

问题描述

我找到了很多关于如何在列表框中查找所选项目以及如何遍历列表框的示例;

for(int index=0;index < listBox1.Items.Count; index++)
{
    MessageBox.Show(listBox1.Items[index].ToString();
}

或者

foreach (DataRowView item in listBox1.Items)
{
   MessageBox.Show(item.Row["ID"].ToString() + " | " + item.Row["bus"].ToString());
}

虽然这些方法对选定的项目很有效,但我还没有弄清楚或找到的是如何获取列表框中每个项目的选定状态、选定和未选定状态,因为上面只给出了选定项。基本上,我需要这样的东西;

for(int index=0;index < listBox1.Items.Count; index++)
{
    if (index.SelectedMode == SelectedMode.Selected)
    {
        MessageBox.Show(listBox1.Items[index].ToString() +"= Selected";
    }
    else
    {
        MessageBox.Show(listBox1.Items[index].ToString() +"= Unselected";
    }
}

我找到了一个片段,它说使用 (listBox1.SelectedIndex = -1) 来确定选定的状态,但是我还没有想出或找到如何围绕它建立一个循环来检查列表框中的每个项目。

我还读到我应该将列表框项目放入一个数组中,但同样没有关于获取列表框中每个项目的选定状态。

我知道我必须遍历列表框来完成我需要的东西,很确定它会是上述循环之一,但是我还没有找到如何提取列表框中每个项目的选定状态。

我正在使用 VS2013、C# Windows 窗体、.NET Framework 4.0 提前感谢任何建议/指导。

标签: c#winformslistboxselecteditem

解决方案


您可以GetSelected使用ListBox. 它返回一个值,指示是否选择了指定的项目。

例如,如果选择了索引 0 处的项目(第一项),则以下代码设置 的selectedtrue

var selected = listBox1.GetSelected(0);

例子

以下循环显示每个项目的消息框,显示项目文本和项目选择状态:

for (int i = 0; i < listBox1.Items.Count; i++)
{
    var text = listBox1.GetItemText(listBox1.Items[i]);
    var selected = listBox1.GetSelected(i);
    MessageBox.Show(string.Format("{0}:{1}", text, selected ? "Selected" : "Not Selected"));
}

推荐阅读