c# - 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 提前感谢任何建议/指导。
解决方案
您可以GetSelected
使用ListBox
. 它返回一个值,指示是否选择了指定的项目。
例如,如果选择了索引 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"));
}
推荐阅读
- python - 使用 pyodbc 禁用触发器
- go - Go 中空接口的最佳实践?
- go - 是否有具有“参考语义”的 Go 类型的通用名称,例如 map、slice 和 channel?
- java - 为什么图形从 CardLayout 中消失了?
- javascript - 动态更新复选框输入的状态
- nginx - 我可以影响 nginx-ingress 中返回的 mime 类型吗?
- python - Django NameError at /HomeFeed/comments/testuser1-12 name 'slug' is not defined
- angular - 如何使用过滤器方法根据角度中的数组字段值过滤数组
- android - 如何使浮动布局在 kivymd 中具有滚动视图?
- python - 在 Plotly Dash 和 Power BI 之间,我应该学习哪一个来获得类似的结果?