Checking TreeView Control Nodes and SubNodes - StackOverflowException! - c#

I have a Tree View control for a Windows Application that uses the CheckBoxes property.
Sometimes (often) when a Tree Node is either checked or unchecked, I get Stack Overflow Exceptions in my static methods below.
Could someone point out why? Maybe even show me how to do this the right way?
In the After Check Event, I have written the following:
void TreeNode_AfterCheck(object sender, TreeViewEventArgs e) {
if (0 < e.Node.Nodes.Count) {
if (e.Node.Checked) {
e.Node.Expand();
TreeNodes_SetChecksTo(e.Node, true);
} else {
if (!TreeNode_SomethingChecked(e.Node)) {
e.Node.Collapse(false);
}
}
}
}
Generally, the Exception is thrown when something in a static method fires the After Check Event above and trickles into one of the static methods below:
static void TreeNodes_SetChecksTo(TreeNode node, bool value) {
if (node != null) {
if (node.Checked != value) node.Checked = value;
if (0 < node.Nodes.Count) {
foreach (TreeNode sub in node.Nodes) {
TreeNodes_SetChecksTo(sub, value);
}
}
}
}
static bool TreeNode_SomethingChecked(TreeNode node) {
if (node != null) {
if (node.Checked) return true;
if (0 < node.Nodes.Count) {
foreach (TreeNode sub in node.Nodes) {
if (TreeNode_SomethingChecked(sub)) {
return true;
}
}
}
}
return false;
}

Setting IsChecked inside TreeNodes_SetChecksTo is resulting in the AfterCheck event being raised and thus the TreeNode_AfterCheck method being called. I suspect you want to disable/ignore the event whilst processing it:
private bool latch;
void TreeNode_AfterCheck(object sender, TreeViewEventArgs e) {
if (latch)
return;
latch = true;
try
{
if (0 < e.Node.Nodes.Count) {
if (e.Node.Checked) {
e.Node.Expand();
TreeNodes_SetChecksTo(e.Node, true);
} else {
if (!TreeNode_SomethingChecked(e.Node)) {
e.Node.Collapse(false);
}
}
}
}
finally
{
latch = false;
}
}

if (node.Checked != value) node.Checked = value;
This is the statement that probably causes it. It fires the AfterCheck event. Your event handler will get called again, while it is already running. You need to protect yourself against that and break the recursion with a private field. Something like this:
private bool updatingChecks;
void TreeNode_AfterCheck(object sender, TreeViewEventArgs e) {
if (updatingChecks) return;
updatingChecks = true;
try {
// etc..
}
finally {
updatingChecks = false;
}
}

The tree is iterated recursively every time a (sub-) node gets checked or unchecked and this happens pretty often as you react on every check state change with your AfterCheck callback. Either "forbid" the callback while an "instance" of it is already processing or do it without explicit recursion and let the callback do the recursion implicitly.

Related

Beginner: TreeView with checkboxes and recursion in Winforms

first post and a new coder so bare with me if you need more info than I am giving. I am trying to create a treeview with checkboxes in a hierarchy (see pic). My issue is i want to create some sort of recursion which deselects and selects child nodes when parent nodes are checked or vice versa.
I am using VS with winforms and been googling for 2 days on how to do this, unfortunately the examples online are either too advanced for me or dont work. I found a Tutorial on how to do this exactly with indeterminate checkboxes as well which would be a big bonus but it is for WPF.
I managed to create buttons which are able to (un)check all buttons with some examples online. Please can someone guide, a beginner who is finding programming AMAZING so far, in the right direction :)
private void button_checkAllNodes_Click(object sender, EventArgs e)
{
checkAllNodes(treeView1.Nodes);
}
private void button_uncheckAllNodes_Click(object sender, EventArgs e)
{
UncheckAllNodes(treeView1.Nodes);
}
public void checkAllNodes(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
node.Checked = true;
checkChildren(node, true);
}
}
public void UncheckAllNodes(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
node.Checked = false;
checkChildren(node, false);
}
}
private void checkChildren(TreeNode rootNode, bool isChecked)
{
foreach (TreeNode node in rootNode.Nodes)
{
checkChildren(node, isChecked);
node.Checked = isChecked;
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
}
Picture Treeview with (un)check All buttons
Let's create a couple of extension methods for the TreeNode type, one that gets all the children of a node, and another that gets it's parents.
// Within your project's namespace...
static class TreeViewExtensions
{
public static IEnumerable<TreeNode> Children(this TreeNode node)
{
foreach (TreeNode n in node.Nodes)
{
yield return n;
foreach (TreeNode child in Children(n))
yield return child;
}
}
public static IEnumerable<TreeNode> Parents(this TreeNode node)
{
var p = node.Parent;
while (p != null)
{
yield return p;
p = p.Parent;
}
}
}
Now, all what you need to do is to handle the TreeView.AfterCheck event to toggle the Checked property of the nodes that the extension methods yield.
// +
using System.Linq;
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action == TreeViewAction.Unknown) return;
foreach (TreeNode n in e.Node.Children())
n.Checked = e.Node.Checked;
// Comment this if you don't need it.
foreach (TreeNode p in e.Node.Parents())
p.Checked = p.Nodes.OfType<TreeNode>().Any(n => n.Checked);
}
Soon, you'll notice sometimes this solution won't work as it should when you click rapidly over the check boxes since they don't receive the mouse double click messages by default. Then, follow this post or this to solve this problem. For now click slowly.
If you prefer though to use buttons to toggle the check state, then delete the AfterCheck handler and do instead:
private void btnCheckAll_Click(object sender, EventArgs e)
{
ToggleCheck(treeView1.SelectedNode, true);
}
private void btnUncheckAll_Click(object sender, EventArgs e)
{
ToggleCheck(treeView1.SelectedNode, false);
}
private void ToggleCheck(TreeNode node, bool state)
{
node.Checked = state;
foreach (TreeNode n in node.Children())
n.Checked = state;
// Optional...
foreach (TreeNode n in node.Parents())
n.Checked = state;
}
I agree with #jdweng , you are using recursion in checkChildren(). The base case is missing.
In recursion checkChildren , add base case before
foreach (TreeNode node in rootNode.Nodes)
if node is Null : rootNode=isChecked

C# TreeView becomes missmatched between data and display

I have a TreeView with checkboxes like
I have added some code to show what is selected:
/// <summary>
/// Highlight checked nodes
/// </summary>
private void HighlightCheckedNodes()
{
foreach (TreeNode topNode in treeView1.Nodes)
{
if (topNode.Checked)
{
topNode.BackColor = Color.Yellow;
}
else
{
topNode.BackColor = Color.White;
}
foreach (TreeNode myNode in topNode.Nodes)
{
// Check whether the tree node is checked.
if (myNode.Checked)
{
// Set the node's backColor.
myNode.BackColor = Color.Yellow;
}
else
{
myNode.BackColor = Color.White;
}
}
}
}
This function is called from treeView1_AfterSelect and treeView1_AfterCheck.
If I click a few times I get some nodes that are marked as checked but not yellow (the data says it's not checked) or vice versa.
So how do I make sure the data and display are in sync?
Long story short, the TreeView is buggy!
Here's an implementation that uses NativeWindow instead of deriving from TreeView. This will allow you to use the existing TreeView on your Form:
public partial class Form1 : Form
{
private TreeViewSuppressDoubleClick treeViewHelper;
private void Form1_Load(object sender, EventArgs e)
{
treeViewHelper = new TreeViewSuppressDoubleClick(this.treeView1);
}
public class TreeViewSuppressDoubleClick : NativeWindow
{
public TreeViewSuppressDoubleClick(TreeView treeView)
{
if (treeView != null && treeView.IsHandleCreated)
{
this.AssignHandle(treeView.Handle);
}
}
protected override void WndProc(ref Message m)
{
if (m.Msg != 0x203)
base.WndProc(ref m);
}
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
e.Node.BackColor = e.Node.Checked ? Color.Yellow : Color.White;
}
}
After this you'll notice that the TreeView isn't as responsive to clicks, but it does stay in sync now.
Note the simplified method for changing the BackColor on a check/uncheck.
Also, here's an alternate HighlightCheckedNodes() using recursion to get all the nodes:
private void HighlightCheckedNodes(TreeNode node)
{
if (node == null)
{
foreach (TreeNode topNode in treeView1.Nodes)
{
HighlightCheckedNodes(topNode);
}
}
else
{
node.BackColor = node.Checked ? Color.Yellow : Color.White;
foreach (TreeNode curNode in node.Nodes)
{
HighlightCheckedNodes(curNode);
}
}
}
You'd call it using HighlightCheckedNodes(null);.

WPF How to raise an Individual property change from DataGrid bounded to a ObservableCollection

As the question ask, how is this done ?
From a DataGrid I can get the SelectedRow of that collection that has been bounded to its ItemSource, but I really need a setter and getter for an individual property that belongs inside the ObservableCollection.
For example, I need to catch when a user checks a bool property inside a datagrid, so then the setter would be set to "false/true". So something like
//But the Archive property is in the DataContext of the row item...
//so this wouldnt work, I think..
private bool m_Archived = false;
public bool Archived
{
get { return m_Archived; }
set
{
m_Archived = value;
OnPropertyChanged("Archived");
}
}
But remember this property is part of the ObservableCollection (DataContext)
Cheers
You need to register to each collection item property changed, then to control when the desired property has changed, then change the archived property. Check this sample code:
private ObservableCollection<TClass> _SomeObservableCollection;
public ObservableCollection<TClass> SomeObservableCollection
{
get { return _SomeObservableCollection ?? (_SomeObservableCollection = SomeObservableCollectionItems()); }
}
private ObservableCollection<TClass> SomeObservableCollectionItems()
{
var resultCollection = new ObservableCollection<TClass>();
foreach (var item in SomeModelCollection)
{
var newPoint = new TClass(item) {IsLocated = true};
newPoint.PropertyChanged += OnItemPropertyChanged;
resultCollection.Add(newPoint);
}
resultCollection.CollectionChanged += OnSomeObservableCollectionCollectionChanged;
return resultCollection;
}
private void OnSomeObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (TClass TClass in e.NewItems)
{
TClass.PropertyChanged += OnItemPropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (TClass TClass in e.OldItems)
{
TClass.PropertyChanged -= OnItemPropertyChanged;
}
}
if (!Patient.HasChanges)
Patient.HasChanges = true;
}
private void OnItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != "ItemArchivedProperty") return;
// set Archived = true or set Archived = false
}
This is just an example, but it should works. Hope it helps.

TreeView with CheckBoxes in c#

I have a tree view with checkboxes in c#, I want that when the user checks one node all the nodes that there are on the levels below automatic checked also.
Does anyone know about way to do that without run with recorsive fnction on all the tree each time that the user checks some node?
Thanks
//this function returns the treeView.
public TreeView GetTreeView()
{
getSubject();
// fill the treeview with all subjects.
foreach (Subject subject in subjects)
{
//for each root subject fill all the his children.
if (subject.subjestId == subject.parentSubject)
{
TreeNode node = new TreeNode(subject.subjectString, subject.subjestId, subject.subjestId);
addChild(node, subject.subjestId);
tv.Nodes.Add(node);
}
}
return tv;
}
// for each subject return sub subjects.
private void addChild(TreeNode node, int parentId)
{
foreach (Subject subject in subjects)
{
if (subject.parentSubject == parentId && subject.parentSubject != subject.subjestId)
{
TreeNode childNode = new TreeNode(subject.subjectString, subject.subjestId, subject.subjestId);
addChild(childNode, subject.subjestId);
node.Nodes.Add(childNode);
}
}
}
Recursion. Like this:
bool busy = false;
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {
if (busy) return;
busy = true;
try {
checkNodes(e.Node, e.Node.Checked);
}
finally {
busy = false;
}
}
private void checkNodes(TreeNode node, bool check) {
foreach (TreeNode child in node.Nodes) {
child.Checked = check;
checkNodes(child, check);
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {
foreach (TreeNode child in e.Node.Nodes) {
child.Checked = e.Node.Checked;
}
}
This is a better solution
private void trvMenuList_AfterCheck(object sender, TreeViewEventArgs e)
{
SetChildrenChecked(e.Node, e.Node.Checked);
}
private void SetChildrenChecked(TreeNode treeNode, bool checkedState)
{
foreach (TreeNode item in treeNode.Nodes)
{
if (item.Checked != checkedState)
{
item.Checked = checkedState;
}
SetChildrenChecked(item, item.Checked);
}
}
As a number of the answers state, create a recursive 'set checked to children' function, then call it AfterCheck on the tree.
The framework unfortunately gives you a call back to AfterCheck even if you set the check value in code, and although this may not be noticeable in small trees adds a massive amount of exponential extra work for your app to do. To avoid it, filter AfterCheck to only fire your new function if it has been triggered by user.
private void tree_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action != TreeViewAction.Unknown)
{
SetChildrenChecked(e.Node);
}
}
private void SetChildrenChecked(TreeNode treeNode)
{
foreach (TreeNode item in treeNode.Nodes)
{
if (item.Checked != treeNode.Checked)
{
item.Checked = treeNode.Checked;
}
if (item.Nodes.Count > 0)
{
SetChildrenChecked(item);
}
}
}
I expanded on the answer a little; by updating the parent as well. [The DisplayException method inside the catch is just a popup window that I always use; you can do your own]
private bool _busy = false;
private void treeViewPassFail_AfterCheck(object sender, TreeViewEventArgs e)
{
try
{
if (_busy)
{
return;
}
_busy = true;
CheckNodes(e.Node, e.Node.Checked);
CheckParent(e.Node.Parent);
}
catch(Exception ex)
{
DisplayException(ex);
}
finally
{
_busy = false;
}
}
private void CheckNodes(TreeNode node, bool check)
{
foreach(TreeNode child in node.Nodes)
{
child.Checked = check;
CheckNodes(child, check);
}
}
private void CheckParent(TreeNode parent)
{
if (parent != null)
{
bool allChecked = true;
foreach (TreeNode node in parent.Nodes)
{
allChecked &= node.Checked;
}
parent.Checked = allChecked;
}
}
If you want to do it in WinForms then I think you have to do it manually by recursion - I don't know any better way.

Differentiating between events raised by user interaction and my own code

The SelectedIndexChanged event gets fired in my application from a combo box when:
the user chooses a different
item in the combo box, or when:
my own code updates the combo
box's SelectedItem to reflect that
the combo box is now displaying
properties for a different object.
I am interested in the SelectedIndexChanged event for case 1, so that I can update the current object's properties. But in case 2, I do not want the event to fire, because the object's properties have not changed.
An example may help. Let's consider that I have a list box containing a list of people and I have a combo box representing the nationality of the currently selected person in the list. Case 1 could happen if Fred is currently selected in the list, and I use the combo box to change his nationality from English to Welsh. Case 2 could happen if I then select Bob, who is Scottish, in the list. Here, my list update event-handler code sees that Bob is now selected, and updates the combo box so that Scottish is now the selected item. This causes the combo box's SelectedIndexChanged event to be fired to set Bob's nationality to Scottish, even though it already is Scottish.
How can I update my combo box's SelectedItem property without causing the SelectedIndexChanged event to fire? One way would be to unregister the event handler, set SelectedItem, then re-register the event handler, but this seems tedious and error prone. There must be a better way.
I created a class I called SuspendLatch. Offers on a better name are welcome, but it does what you need and you would use it like this:
void Method()
{
using (suspendLatch.GetToken())
{
// Update selected index etc
}
}
void listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (suspendLatch.HasOutstandingTokens)
{
return;
}
// Do some work
}
It's not pretty, but it does work, and unlike unregistering events or boolean flags, it supports nested operations a bit like TransactionScope. You keep taking tokens from the latch and it's only when the last token is disposed that the HasOutstandingTokens returns false. Nice and safe. Not threadsafe, though...
Here's the code for SuspendLatch:
public class SuspendLatch
{
private IDictionary<Guid, SuspendLatchToken> tokens = new Dictionary<Guid, SuspendLatchToken>();
public SuspendLatchToken GetToken()
{
SuspendLatchToken token = new SuspendLatchToken(this);
tokens.Add(token.Key, token);
return token;
}
public bool HasOutstandingTokens
{
get { return tokens.Count > 0; }
}
public void CancelToken(SuspendLatchToken token)
{
tokens.Remove(token.Key);
}
public class SuspendLatchToken : IDisposable
{
private bool disposed = false;
private Guid key = Guid.NewGuid();
private SuspendLatch parent;
internal SuspendLatchToken(SuspendLatch parent)
{
this.parent = parent;
}
public Guid Key
{
get { return this.key; }
}
public override bool Equals(object obj)
{
SuspendLatchToken other = obj as SuspendLatchToken;
if (other != null)
{
return Key.Equals(other.Key);
}
else
{
return false;
}
}
public override int GetHashCode()
{
return Key.GetHashCode();
}
public override string ToString()
{
return Key.ToString();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Dispose managed resources.
parent.CancelToken(this);
}
// There are no unmanaged resources to release, but
// if we add them, they need to be released here.
}
disposed = true;
// If it is available, make the call to the
// base class's Dispose(Boolean) method
//base.Dispose(disposing);
}
}
}
I think the best way would be to use a flag variable:
bool updatingCheckbox = false;
void updateCheckBox()
{
updatingCheckBox = true;
checkbox.Checked = true;
updatingCheckBox = false;
}
void checkbox_CheckedChanged( object sender, EventArgs e )
{
if (!updatingCheckBox)
PerformActions()
}
[Edit: Posting only the code is not really clear]
In this case, the event handler wouldn't perform its normal operations when the checkbox is changed through updateCheckBox().
I have always used a boolean flag variable to protect against unwanted event handlers. The TaskVision sample application taught me how to do this.
Your event handler code for all of your events will look like this:
private bool lockEvents;
protected void MyEventHandler(object sender, EventArgs e)
{
if (this.lockEvents)
{
return;
}
this.lockEvents = true;
//Handle your event...
this.lockEvents = false;
}
I let the event fire. But, I set a flag before changing the index and flip it back after. In the event handler, I check if the flag is set and exit the handler if it is.
I think your focus should be on the object and not on the event that's occuring.
Say for example you have the event
void combobox_Changed( object sender, EventArgs e )
{
PerformActions()
}
and PerformActions did something to the effect of
void PerformActions()
{
(listBox.SelectedItem as IPerson).Nationality =
(comboBox.SelectedItem as INationality)
}
then inside the Person you would expect to see something to the effect of
class Person: IPerson
{
INationality Nationality
{
get { return m_nationality; }
set
{
if (m_nationality <> value)
{
m_nationality = value;
this.IsDirty = true;
}
}
}
}
the point here is that you let the object keep track of what is happening to itself, not the UI. This also lets you keep track of dirty flag tracking on your objects, which could be useful for persistence later on.
This also keeps your UI clean and keeps it from getting odd event registration code that will most likely be error prone.
I have finally found a solution to avoid the uncessary event from being fired too many time.
I use a counter and I only hook/unhook the events I want to mask once when it is not needed, and when it is needed again.
The example below shows how I hide the CellValueChanged event of a datagrid.
EventMask valueChangedEventMask;
// In the class constructor
valueChangedEventMask = new EventMask(
() => { dgv.CellValueChanged += new DataGridViewCellEventHandler(dgv_CellValueChanged); },
() => { dgv.CellValueChanged -= new DataGridViewCellEventHandler(dgv_CellValueChanged); }
);
// Use push to hide the event and pop to make it available again. The operation can be nested or be used in the event itself.
void changeCellOperation()
{
valueChangedEventMask.Push();
...
cell.Value = myNewCellValue
...
valueChangedEventMask.Pop();
}
// The class
public class EventMask
{
Action hook;
Action unHook;
int count = 0;
public EventMask(Action hook, Action unHook)
{
this.hook = hook;
this.unHook = unHook;
}
public void Push()
{
count++;
if (count == 1)
unHook();
}
public void Pop()
{
count--;
if (count == 0)
hook();
}
}

Categories

Resources