首页 文章

C#查找ListBox中所有项的Selected State

提问于
浏览
0

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

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提前感谢任何建议/方向 .

2 回答

  • 1

    这将为您提供未选择的项目:

    List<string> unselected = listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>());
    

    您可以像这样遍历该列表:

    foreach(string str in listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>()))
    {
        System.Diagnostics.Debug.WriteLine($"{str} = Not selected");
    }
    

    我've made the assumption that you'使用 string 作为您的项目类型 . 如果你想使用别的东西,那么只需用你的类型替换 string ,它应该仍然有用 .

    然后循环遍历未选择的项目以使用它们执行任何操作然后循环 listBox1.SelectedItems 以使用所选项目执行任何操作 .

  • 1

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

    例如,如果选择索引0处的项目(第一个项目),则以下代码将 selected 的值设置为 true

    var selected = listBox1.GetSelected(0);
    

    Example

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

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

相关问题