【问题标题】:How do I find out if individual items in CheckedListBox are checked? C#如何确定 CheckedListBox 中的单个项目是否被选中? C#
【发布时间】:2023-04-02 23:30:01
【问题描述】:

我试过查看checkedListBox1.Items,但这没有帮助。那么如何检查 CheckedListBox 中的项目是否被标记?它在一个 Windows 窗体应用程序中。

【问题讨论】:

  • 您使用的是MVC 还是Website
  • 这个问题的质量很差。我们这里的上下文很少,这几乎不可能回答。尝试提供代码示例,说明您尝试过的方法、使用的技术以及遇到的问题。
  • 还是 Windows 窗体或 WPF?
  • 对于质量不佳的问题,我很抱歉,我刚加入该网站,希望能得到一些帮助。我现在正在学习 C# 课程,我需要我能得到的所有帮助。

标签: c# winforms checkedlistbox


【解决方案1】:

您可以使用CheckedItems 属性获取已检查项目的列表。

示例 1:

foreach (var item in this.checkedListBox1.CheckedItems)
{
    MessageBox.Show(item.ToString());
}

示例 2:

this.checkedListBox1.CheckedItems.Cast<object>()
    .ToList()
    .ForEach(item =>
    {
        //do stuff here
        //for example
        MessageBox.Show(item.ToString());
    });

如果您确定项目是string,例如,您可以在上面的代码中使用Cast&lt;object&gt;

您可以使用CheckedIndices 属性获取已检查索引的列表。

示例:

this.checkedListBox1.CheckedIndices.Cast<int>()
    .ToList()
    .ForEach(index =>
    {
        //do stuff here
        //for example
        MessageBox.Show(this.checkedListBox1.Items[index].ToString());
    });

【讨论】:

  • 在两个 LINQ 示例中,.ToList() 不是必需的。
  • @RichardSchneider 据我所知ForEachList&lt;T&gt; 的成员ForEach 是否存在IEnumerable&lt;T&gt; 的扩展方法?
【解决方案2】:

试试这个:

 foreach (ListItem item in checkedListBox1.Items)
        {
            if (item.Selected)
            {
                // If the item is selected 

            }
            else
            {
                // Item is not selected, do something else.
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 2010-11-13
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多