.NET Listbox: in ItemChecked event know if item was clicked
I have a ListBox in my winforms app and I need to handle the ItemChecked becaue each time the users cliks an item i need to some stuff. The problem is that I also need to change the Checked property in some other events of the form. In those cases I need to avoid do that stuff.
Example:
private void listBox1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if (true) //Should check if item was clicked.
{
开发者_开发技巧//Do some stuff
}
else //If the event was fired because I changed the Checked property from the code
{
//Do some other stuff
}
}
Thanks
If I understand you correctly, I think you want to unsubscribe to the ItemCheck event when you are changing the Checked property behind the scenes (i.e. the user didnt cause the Checked property to change).
So for example:
public void SetupListBoxEnables()
{
// Do not listen for Checked change events
listBox1.ItemCheck -= listBox1_ItemChecked;
// Change a bunch of Checked properties
// ....
// Listen again for Checked change events
listBox1.ItemCheck += listBox1_ItemChecked;
}
One way would be to use a bool variable let's say ManualRaise. When you are raising the event through code, set ManualRaise = true and inside your event you can check '
if(ManualRaise)
{
// this was manual event raise
ManualRaise = False
}
else
{
}
and in that event where you will raise the list box event, set the ManualRaise to true.
I keep a Boolean value in the class to keep track of when actions are performed by the user or automatically by the system. Whenever I am about to change, for example, CheckBox.Checked, I set the Boolean to True, then back to False after I'm done.
In the Checked event handler, I check to see if the event occurred while the Boolean is true to determine which code to execute.
private Boolean blnSystem = false;
private void SystemChanges()
{
try
{
blnSystem = true;
//Code which changes listBox1 Item Checked values
}
catch
{
//Error handler
}
finally
{
blnSystem = false;
}
}
private void listBox1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
if (!blnSystem) //Should check if item was clicked.
{
//Do some stuff
}
else //If the event was fired because I changed the Checked property from the code
{
//Do some other stuff
}
}
All of the answers you have gotten so far are great. I'm wondering, however, if it might make more sense to put the logic that is specific to programmatic setting the selected list item in the same code that actually sets the checked property rather than rely on the ItemChecked event. The event can call the same code that the previous code does.
example:
public void SomeFunction()
{
// set checkbox
listBox1.Items[index].Checked = true;
// Handle the change in state
HandleState();
}
protected void listBox1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
HandleState();
}
private function HandleState()
{
// Handle your visual state here
}
精彩评论