Nothing is everything.

Wednesday, December 30, 2009

Event Recursion Problem

We often meet some issues that an event will be fired recursively and its handlers will also be called recursively. Below is a sample which shows a AfterCheck event handler of the TreeView in similar circumstances:

void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Node.Nodes.Count > 0)
{
foreach (TreeNode subNode in e.Node.Nodes)
{
//This property setting will firing the AfterCheck event again.
subNode.Checked = true;
}
}
}


To control the event firing and handler calling, we need to create our own TreeView control and override the OnAfterCheck method to control the event firing. There are four requirements below:



1. The event should be fired recursively and its handlers can also be called recursively.

        In this case, we need to do nothing.



2. The event should be fired only once and its handlers can only be called once as well.

       



public class MyTreeView : TreeView
{
//Indicate if the event should be fired.
private bool IsFire = true;
protected override void OnAfterCheck(TreeViewEventArgs e)
{
if (IsFire)
{
IsFire = false;

//Your Code in the old AfterCheck event handler.

IsFire = true;
base.OnAfterCheck(e);
}
}
}


3. The event should be fired recursively but the handler can only be called once.


public class MyTreeView : TreeView
{
//Indicate if the event should be fired.
private bool IsFire = true;
protected override void OnAfterCheck(TreeViewEventArgs e)
{
if (IsFire)
{
IsFire = false;

//Your Code in the old AfterCheck event handler.

IsFire = true;
base.OnAfterCheck(e);
}
else
{
base.OnAfterCheck(e);
}
}
}


4. The handler should be called recursively but the event can only be fired once.


public class MyTreeView : TreeView
{
//Indicate if the event should be fired.
private bool IsFire = true;
protected override void OnAfterCheck(TreeViewEventArgs e)
{
if (IsFire)
{
IsFire = false;

//Your Code in the old AfterCheck event handler.

IsFire = true;
base.OnAfterCheck(e);
}
else
{
//Your Code in the old AfterCheck event handler.
}
}
}


Please feel free to tell me if I made some mistakes. Thanks.

No comments:

Post a Comment

Followers