C# Find the Selected State of all items in a ListBox

时间:2018-08-24 18:55:05

标签: c# winforms listbox selecteditem

I have found many examples on how to find the selected items in a listbox and how to iterate through a listbox;

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

or

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

While these methods work great for the selected items, what I have yet to figure out, or find, is how to get the selected state, selected and unselected, of every item in a listbox, as the above only gives the selected. Basically, I need something like this;

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

I've found a snippet that said to use (listBox1.SelectedIndex = -1) to determine the selected state however I've not figured out or found how to build a loop around this to check each item in the listbox.

I've also read that I should put the listbox items into an array, but again nothing about getting the selected state of each item in the listbox.

I know I'll have to iterate through the listbox to accomplish what I'm needing, pretty sure it'll be one of the above loops, however I have yet to find how to extract the selected state of each item in the listbox.

I'm using VS2013, C# Windows Form, .NET Framework 4.0 Thanks in advance for any advice/direction.

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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");
}

我已经假设您使用string作为商品类型。如果您想使用其他内容,只需将string替换为您的类型,它仍然可以使用。

然后,您遍历未选中的项目以对它们执行任何操作,然后遍历listBox1.SelectedItems以对所选项目进行任何操作。