【问题标题】:Determining Whether a Selected CheckListBox Item is Checked确定是否选中了选定的 CheckListBox 项
【发布时间】:2014-03-13 05:32:44
【问题描述】:

关于 CheckListBox 的信息太少了,我想知道人们是否没有使用其他东西。

我正在尝试对 MouseUp 事件使用条件语句来确定选中的复选框项目是选中还是未选中。以下代码不起作用:

if (clBox.SelectedItem == CheckState.Checked)
{
   //Do something
}

如何确定选中的 CheckListBox 项是否被选中?我必须使用 MouseUP 事件,因为在添加到列表时可能会选中某些框时,使用 ItemCheck 事件很麻烦。否则我最终会触发事件。然而,当他们取消选中该框时,我如何确保某事被撤消而不是在他们选中时完成?

编辑:忘了说这是 Windows 窗体。

【问题讨论】:

    标签: c# checklistbox


    【解决方案1】:

    您可以检查 CheckedItems 集合以查找 SelectedItem 是否包含在其中。试试这样的。

    private void clBox_MouseUp(object sender, MouseEventArgs e)
    {
        if (clBox.CheckedItems.Contains(clBox.SelectedItem))
        {
            MessageBox.Show("Test");
        }
    }
    

    【讨论】:

    • 最终解决了这个问题。我仍然想找出一种使用 MouseUp 的方法,而是使用 ItemCheck 事件,而不是在添加已检查的项目时触发它。谢谢!
    【解决方案2】:

    我假设您在这里关注 WinForms CheckedListBox (CLB)。我认为解决您的问题的更好方法是附加到 CLB 的“ItemCheck”事件。

      private void AttachEvents()
      {
         // ....
         this.checkedListBox.ItemCheck += CheckedListBoxOnItemCheck;
      }
    
      private void CheckedListBoxOnItemCheck(object sender, ItemCheckEventArgs itemCheckEventArgs)
      {
         var item = checkedListBox.Items[itemCheckEventArgs.Index];
         System.Diagnostics.Debug.WriteLine("Item in question: " + item);
         System.Diagnostics.Debug.WriteLine("Previous check state: " + itemCheckEventArgs.CurrentValue);
         System.Diagnostics.Debug.WriteLine("New check state: " + itemCheckEventArgs.NewValue);
      }
    

    根据你的应用需求,你还应该做到以下几点:

    this.checkedListBox.CheckOnClick = true;
    

    然后您的 CLB 将按照大多数用户的预期运行。

    问候, 亚历克斯

    【讨论】:

    • 我假设这将消除在将框添加到触发 ItemCheck 事件的列表时将框设置为选中的问题?
    • 当您使用此事件时,您还会在添加已选中状态的项目时收到通知。例如。当使用this.checkedListBox.Items.Add(someString, true); 时,事件也会被触发。不知道是不是你在评论中问的。
    【解决方案3】:
        <asp:CheckBoxList ID="ck1" runat="server">
        <asp:ListItem Text ="1" Value ="1"></asp:ListItem>
        <asp:ListItem Text ="2" Value ="2"></asp:ListItem>
        <asp:ListItem Text ="3" Value ="3"></asp:ListItem>
        <asp:ListItem Text ="4" Value ="4"></asp:ListItem>
        <asp:ListItem Text ="5" Value ="5"></asp:ListItem>
        </asp:CheckBoxList>
    

    这是您的清单框 ..现在来回答您的问题 ..

    if (chk1.selectedvalue=="1")
    {
    }
    elseif (chk1.selectedvalue=="2")
    {
    }
    elseif (chk1.selectedvalue=="3") 
    {
    }
    elseif (chk1.selectedvalue=="4")
    {
    }
    

    现在您可以检查哪个复选框被选中或不选中

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多