I tried

If (checkedListBox1.SelectedItem.ToString() == "Others")
{
//do something
}

but it's not working the way I wanted to.. Whenever the 'Others' item is checked, the code executes but if I tried to uncheck it, it still execute the code as if it runs when that item is selected checked or unchecked..

Recommended Answers

All 6 Replies

This doesnt check if the Item is Checked, it checks if the Selected item has the text value "Others". You need to check for both if you only want the code to run when the "Others" item is checked:

If (checkedListBox1.SelectedItem.ToString() == "Others" && checkedListBox1.SelectItem.Checked)
{
//do something
}

The SelectedItem is not dependant upon the items checked state.
In a CheckedListBox the SelectedItem is the one the being clicked.

To test if it is checked or unchecked you must call the GetItemChecked function with the SelectedIndex property.
This returns true if the item is checked, false otherwise.

if (checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex))
{
    // do something
}

Note: If this is called in the ItemCheck event, then the checked state of the just clicked item is not yet updated.
See this post for a way around this.

@ryshad

SelectItem is not being recognized..


@nick

How to set the selected index for a specific item?

To get the index of an item use the IndexOf property of the Items collection.

if (checkedListBox1.GetItemChecked(checkedListBox1.Items.IndexOf("Others")))
{
    // do something
}

@Ryshad: My first reaction was also to use a Checked property, but all the items in the CheckedListBox return object!:(

commented: the answer i'm looking for! thanks +1

It's now working just the way I wanted it to! Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.