确定是否选中选定的CheckListBox项

本文关键字:CheckListBox 是否 | 更新日期: 2023-09-27 17:50:11

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

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

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

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

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

确定是否选中选定的CheckListBox项

您可以检查CheckedItems集合以查找其中是否包含SelectedItem。

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

我认为您关心这里的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将按照大多数用户的预期运行。

谨致问候,Alex

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

现在您可以检查哪个复选框是选中的还是不选中