user2244255
user2244255

Reputation:

Check Treeview for changes?

I have a winform showing a Treeview control that gets populated with a whole bunch of nodes whenever the winform opens. My code allows the user to select a node, then open a small dialog, enter a value which then edits the node's text.

Is it possible to check an entire treeview for changes when the user closes the form?

I was thinking of just summing up all nodes into one string and then when closing the form, sum it up again as a new string and compare it with the previously made string, but I think there are be better ways to do this.

Upvotes: 2

Views: 1425

Answers (3)

Hans Passant
Hans Passant

Reputation: 941327

This is a fairly common fallacy, TreeView (like ListBox and ListView) doesn't have an event that notifies that the node collection changed. There's a good reason for that, the user himself cannot do anything to add or remove nodes. Only your code can do that. And there is no way you cannot know about that. Or to put it another way, you don't need to be notified about something you already know.

If you want an event for it then you can add your own. And fire it when your code changes the node collection. Do note that this is a code smell, you almost always want this kind of notification on your model instead of the view.

Upvotes: 2

Dietz
Dietz

Reputation: 578

Short answer: Yes, it is possible.

If you insist on waiting with saving or registering changes till the application is closed, you could write a simple recursive function to traverse the current version (working memory with possible changes) with the old version (loaded from whereever you have it saved). Ill leave implementation to you. Anyways here is some inspiration:

http://en.wikipedia.org/wiki/Tree_traversal

Personally id consider saving any changes made by the user when the the edit form is closed by pressing ok or save.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

Though you could check the TreeView for all changes if you cached the nodes up front, I think the right approach is to manage the changes as they occur. For example, when opening the form that edits the nodes pass in the form you came from like this:

private Form1 _f;

...

public Form2(Form1 f)
{
    this._f = f;
}

and then override the OnClosing method of Form2 like this:

protected override void OnClosing(CancelEventArgs e)
{
    this._f.SetChangedNode(...);
}

and create the SetChangedNode method on Form1. I don't know what those parameters look like, but they are probably something like TreeNode node, string newLabel and then you can easily store those values in a Dictionary<TreeNode, string> and then leverage that Dictionary when closing the application.

Upvotes: 0

Related Questions