Domanda

There is so little information out there about the CheckListBox that I'm wondering if people aren't using something else instead.

I am trying to use a conditional statement on a MouseUp event to determine if the selected check list box item is checked or unchecked. The following code does not work:

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

How can I determine whether or not the selected CheckListBox item is checked? I have to use the MouseUP event because using the ItemCheck event is troublesome when some boxes may be checked when added to the list. Otherwise I end up triggering the event. Yet how do I make sure something is undone when they uncheck the box vs. done when they check it?

EDIT: Forgot to mention that this is Windows Forms.

È stato utile?

Soluzione

You can check the CheckedItems collection to find if the SelectedItem is contained in it. Try something like this.

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

Altri suggerimenti

I assume that you're concerned about the WinForms CheckedListBox (CLB) here. I think a better Approach for your Problem is to attach to the "ItemCheck" Event of the CLB.

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

Depending on your applications Needs, you should also do the following:

this.checkedListBox.CheckOnClick = true;

Then your CLB will behave as most users would expect.

Regards, 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>

this is your checklistbox ..Now come to your question ..

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

Now you can check which check box is check or not

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top