StatusStripLabel dynamically updated - c#

My point is to display number of all child nodes at StatusStripLabel. My point is that I want StatusStripLabel to get updated everytime number of child nodes get's changed - I'll add or delete some of already exists. First, I placed code in Public Form, but it didn't worked as I expected. After some time I came with idea that actually works: I placed the code inside button method. But after that I realized that I'll need to place it in second place, in case of deleting node. So My question is: is there anything that can make it simplier? If my explanation isn't enough, just tell me, I'll try my best.
Code from Public Form (Because I want that counter to work from the beggining, not after I'll press the button)
childNodeCounter();
toolStripStatusLabel1.Text = "Number of games in database: " + NodeCounter.ToString();
Method:
public void childNodeCounter()
{
NodeCounter = 0;
foreach (TreeNode RootNode in treeView1.Nodes)
{
foreach (TreeNode ChildNode in RootNode.Nodes)
{
NodeCounter++;
}
}
toolStripStatusLabel1.Text = "Number of games in database: " + NodeCounter.ToString();
}
Code inside button method:
private void button1_Click(object sender, EventArgs e)
{
NodeCounter = 0;
foreach (TreeNode RootNode in treeView1.Nodes)
{
foreach (TreeNode ChildNode in RootNode.Nodes)
{
NodeCounter++;
}
}
toolStripStatusLabel1.Text = "Number of games in database: " + NodeCounter.ToString();
}
Edit: Thanks to mr. Hans Passant I wrote this and it works very well:
public int childNodeCounter(TreeNodeCollection nodes)
{
int count = 0;
foreach (TreeNode RootNode in nodes)
{
foreach (TreeNode ChildNode in RootNode.Nodes)
count++;
}
return count;
Event handler looks like this:
toolStripStatusLabel1.Text = "Number of games in database: " + childNodeCounter(treeView1.Nodes);

Three tiny optimizations
Rather that iterate the tree yourself, just use ChildNode.Nodes.GetNodeCount
Rather than repeat the same logic in different places, have your button Click events simply call the UpdateNodeCount() method.
The text initializer in the first code fragment is redundant, and can be eliminated: the call to childNodeCounter already does the status label update.

The natural way to traverse a tree structure is by using recursion. That's always a bit hard to reason through but there are lots of resources available. Doing it iteratively is a lot uglier, you have to use a Stack<> to allow you to backtrack again out of a nested node. I'll therefore post the recursion solution:
private static int CountNodes(TreeNodeCollection nodes) {
int count = nodes.Count;
foreach (TreeNode node in nodes) count += CountNodes(node.Nodes);
return count;
}
Then your event handler becomes:
private void button1_Click(object sender, EventArgs e) {
toolStripStatusLabel1.Text = "Number of games in database: " +
CountNodes(treeView1.Nodes);
}

If you're adding and removing "game" nodes to the treeView, you must be having methods like void AddGame(string title) and void RemoveGame(string title) which add/remove (child) nodes - those whose total number you want to count. If I understood well, you want toolStripStatusLabel1.Text to be automatically updated each time the number of child nodes changes. In that case you can add field
private int nodesCount;
to your Form class and have something like this:
void AddGame(string title)
{
if(InvokeRequired)
{
Invoke(new MethodInvoker(delegate() { AddGame(title); }));
}
else
{
AddGameNodeToTreeView(title); // add new game node to desired place in TreeView
nodesCount++; // increase node counter
toolStripStatusLabel1.Text = "Number of games in database: " + nodesCount;
}
}
RemoveGame() would be implemented in the same way (or joined with AddGame() into a single method with one additional argument - bool add). Both methods could be extended if you're adding/removing multiple nodes in which case you'll be passing title array and updating nodesCount accordingly.
The advantage of this approach is that you don't have to count nodes in the tree each time before updating toolStripStatusLabel1.Text. Also, toolStripStatusLabel1.Text is updated automatically, not only when user clicks the button.
Drawback is that nodesCount is somewhat redundant information: total number of nodes of interest is 'hidden' in the treeView. You have to make sure that nodesCount is in sync with the actual number of nodes.

Related

Getting all visible Nodes from Infragistics UltraTree

I have 1 root node and many child nodes of that root node.
I want to get all of the visible nodes key.
The recursive code block like below;
public void PrintNodesRecursive(UltraTreeNode oParentNode)
{
foreach (UltraTreeNode oSubNode in ultraTree1.Nodes[0].Nodes)
{
MessageBox.Show(oSubNode.Key.ToString());
PrintNodesRecursive(oSubNode);
}
}
private void ultraButton3_Click(object sender, EventArgs e)
{
PrintNodesRecursive(ultraTree1.Nodes[0]);
}
However messagebox always show me '1' value. It doesn't count and endless loop happens.
How can I make it happen?
Try like this;
public void PrintNodesRecursive(UltraTreeNode oParentNode)
{
if (oParentNode.Nodes.Length == 0)
{
return;
}
foreach (UltraTreeNode oSubNode in oParentNode.Nodes)
{
if(oSubNode.Visible)
{
MessageBox.Show(oSubNode.Key.ToString());
}
PrintNodesRecursive(oSubNode);
}
}
Also, put the visible condition in the loop.
You made a simple programming error. This line:
foreach (UltraTreeNode oSubNode in ultraTree1.Nodes[0].Nodes)
should probably be
foreach (UltraTreeNode oSubNode in oParentNode.Nodes)
Otherwise, every recursion step starts again from the top.

How to prevent TreeView rename from making a duplicate

I've seen lots of posts asking a question similar to this, but none seem to answer the question. I have a TreeView of vendors like this:
Soda
Regular
SmallCan
SmallBottle
Diet
SmallCan
Water
Regular
EcoBottle
I created a context menu that allows the user to rename the selected node, but cannot find a way to enforce that if it makes a duplicate node name, either the change is refused or the node text is reverted to the previous value. This is the context change event and the method to handle the enforcing:
private void contextMenuRename_Click(object sender, System.EventArgs e)
{
restoreNode = treProducts.SelectedNode;
treProducts.LabelEdit = true;
if (!treProducts.SelectedNode.IsEditing)
{
treProducts.SelectedNode.BeginEdit();
}
enforceNoTreeDuplicates();
}
private void enforceNoTreeDuplicates()
{
nodeNames.Clear();
if (treProducts.SelectedNode.Level != 0)
{
foreach (TreeNode node in treProducts.SelectedNode.Parent.Nodes)
{
nodeNames.Add(node.Text);
}
}
else
{
foreach (TreeNode node in treProducts.Nodes)
{
nodeNames.Add(node.Text);
}
}
int countDuplicates = 0;
foreach (string nodeName in nodeNames)
{
if (restoreNode.Text == nodeName)
{
countDuplicates++;
}
if (countDuplicates > 1)
{
treProducts.SelectedNode = restoreNode;
}
}
}
However, the BeginEdit() doesn't seem to run if the enforceNoTreeDuplicates() method is in there. Is there a better way to handle the editing of the selected node or is there something wrong with the enforceNoTreeDuplicates() method?
Generally, you would use the AfterLabelEdit for that, which has an option to cancel the edit:
void treProducts_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) {
foreach (TreeNode tn in e.Node.Parent.Nodes) {
if (tn.Text == e.Label) {
e.CancelEdit = true;
}
}
}

C# Treeview Indexing

I've got a bit of a problem with treeview and how the indexing of nodes works. In my program, I have a database that can contain any amount of users. Each user is separated by a carriage return (i.e. one user per line). I'm creating a treeview object that lists all users in the database. If the user clicks on a specific node, how do I refer to that node / handle it being selected, as I am dynamically making nodes from the database?
StreamReader getMembers = new StreamReader(#"[data]\db\users.db");
List<string> mems = new List<string>();
members.Nodes.Add("Members");
while (!getMembers.EndOfStream)
{
mems.Add(getMembers.ReadLine());
}
foreach (string o in mems)
{
TreeNode n = new TreeNode(o);
members.Nodes[0].Nodes.Add(n);
}
Database & Program:
If you are trying to get the tree node that was selected you can achieve that by the TreeView.SelectedNode property... (http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.selectednode.aspx)
if you want to handle an event on treenode selected register the TreeView.AfterSelect event (http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.afterselect)
example:
private void TreeView1_AfterSelect(System.Object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
// Vary the response depending on which TreeViewAction
// triggered the event.
switch((e.Action))
{
case TreeViewAction.ByKeyboard:
MessageBox.Show("You like the keyboard!");
break;
case TreeViewAction.ByMouse:
MessageBox.Show("You like the mouse!");
break;
}
}
Assuming you are using the standard forms treeview, it sounds like you want to subscribe to the event on the TreeView.AfterSelect.
// Handle the After_Select event.
private void TreeView1_AfterSelect(System.Object sender,
System.Windows.Forms.TreeViewEventArgs e)
{
// If (TreeView1.SelectedNode...
}

How to check a form is still 'alive'

I am loading a big treeview in a seperate thread. This thread starts at the load event of a form.
All goes well, until an error occurs in the load event. When an error occurs I close the form and the thread that loads my treeview must be aborted. But I don't know how to do this.
The problem is, that the form is closed and the thread is still working, so I get an InvalidOperationException. The program breaks down and this part of the thread is highlighted:
tvQuestionnaire.Invoke((MethodInvoker)delegate
{
tvQuestionnaire.Nodes.Add(catNode);
});
The treeview on my form is called tvQuestionnaire. The whole function (which is called in my background worker) looks like this:
private void SetTreeviewData()
{
// Get all categories
List<Category> categories = _questionnaire.GetCategoriesFromQuestionnaire();
// Get all questions which are retrieved by the question manager
OrderedDictionary all_ordered_questions = _questionManager.AllQuestions;
// Store all the questions in a List<T>
List<Question> all_questions = new List<Question>();
foreach (DictionaryEntry de in all_ordered_questions)
{
Question q = de.Value as Question;
all_questions.Add(q);
}
foreach (Category category in categories)
{
// Create category node
TreeNode catNode = new TreeNode();
catNode.Text = category.Description;
catNode.Tag = category;
catNode.Name = category.Id.ToString();
// Get all questions which belongs to the category
List<Question> questions = all_questions.FindAll(q => q.CategoryId == category.Id);
// Default set the font to bold (Windows issue)
Font font = new Font(tvQuestionnaire.Font, FontStyle.Regular);
foreach (Question question in questions)
{
// Create question node
TreeNode queNode = new TreeNode();
queNode.Text = question.Question;
queNode.Tag = question;
queNode.Name = "Q" + question.Id;
queNode.NodeFont = font;
// Determine which treenode icon to show
SetTreeNodeIcon(ref queNode, question);
// Add node to category node
catNode.Nodes.Add(queNode);
}
if (_closing)
return;
// Add category node to treeview
tvQuestionnaire.Invoke((MethodInvoker)delegate
{
tvQuestionnaire.Nodes.Add(catNode);
// Now the category (and thus the questions) are added to treeview
// Set questions treenode icon
//SetTreeNodeIcon(questions);
});
}
// Set each category under its parent
for (int i = tvQuestionnaire.Nodes.Count - 1; i >= 0; i--)
{
Category category = tvQuestionnaire.Nodes[i].Tag as Category;
TreeNode node = tvQuestionnaire.Nodes[i];
if (IsWindow(this.Handle.ToInt32()) == 0)
return;
tvQuestionnaire.Invoke((MethodInvoker)delegate
{
if (category.ParentId == null)
return;
else
{
// Find parent node
TreeNode[] parentNodes = tvQuestionnaire.Nodes.Find(category.ParentId.ToString(), true);
//Remove current node from treeview
tvQuestionnaire.Nodes.Remove(node);
parentNodes[0].Nodes.Insert(0, node);
}
});
}
}
This is the only method that my background worker calls.
So my question is, how can I prevent that the Exception occurs? How do I check the form where the treeview is on, is still 'alive'?
One solution would be to call the CancelAsync method of the backgroundworker (BGW) when you need to close the form. In the DoWork event handler, check at the beginning of the loop that cancellation has not been requested. If it was, exit the loop (and the DoWork handler).
In the form, wait for the BGW to complete (either success or cancellation)
Why not catch this event, than abort the thread's execution?
Check IsHandleCreated property of a form. If the form is still alive, it will true.

Slow TreeNode with CheckBoxes [large quantity]

Tree View control's AfterCheck event checks all child nodes below it and enables the Run button if something is checked.
1346 void TreeNode_AfterCheck(object sender, TreeViewEventArgs e) {
1347 if (!e.Node.Checked) return;
1348 foreach (TreeNode sub in e.Node.Nodes) {
1349 sub.Checked = e.Node.Checked;
1350 }
1351 RunButton.Enabled = IsANodeChecked();
1352 }
1429 static bool IsANodeChecked(TreeNode node) {
1430 if (node.Checked) return true;
1431 foreach (TreeNode sub in node.Nodes) {
1432 if (IsANodeChecked(sub)) {
1433 return true;
1434 }
1435 }
1436 return false;
1437 }
Checking the root node when there are 4881 sub nodes will hang the GUI for about 7 seconds.
I only need to call IsANodeChecked (on Line 1351) once, but I don't know how to disable it until after all of the tree nodes have been processed.
And I do not want to have a timer on my form devoted to monitoring this.
Does anyone see a simple/obvious solution?
Put an event handler on your checkboxes that enables or disables the RunButton as opposed to having something that iterates over the whole thing to find out.
Add the checkbox to a list of checked checkboxes when it get's checked first so you don't disable the RunButton until the list of checked checkboxes is empty. Remove it from the list when it's unchecked, etc.
Here's kind of how I would write it out, this is just winging it so sorry if I miss something:
private int _checkedCheckboxes;
void AddCheckBox()
{
if (_checkedCheckBoxes++ == 1) RunButton.Enabled = true;
}
void RemoveCheckBox()
{
if (_checkedCheckBoxes-- == 0) RunButton.Enabled = false;
}
void TreeNode_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Node.Checked)
{
AddCheckBox();
return;
}
RemoveCheckBox();
}
I sometimes use a Timer to handle such cases. Add a timer and set up the Tick event handler to call IsANodeChecked and enable/disable the button. Give it a short interval (~100 ms perhaps), and leave it disabled. Then, you call Stop followed by Start on the timer in your AfterCheck event handler. This will cause the timer to be restarted for each call to AfterCheck, but the Tick event handler will be invoked only when a certain time has elapsed after the Start call, which means that it will not be invoked until after the last call to AfterCheck.
100 ms is a very long time for the computer to work, but will seem immediate for the user.
You can see similar behavior in the Windows Explorer. If you use the keyboard to quickly navigate around in the folder tree, the right hand pane with the folder contents will not update unless you stay on a folder in the tree for a brief moment.
These ideas where helpful, but I used something different that worked by adding a single boolean variable:
bool _treeNodeFirst = false;
...and a Before Checked event that temporarily modifies the Back Color on the control to serve as a flag for the control that started the chain of events:
1273 void TreeNode_BeforeCheck(object sender, TreeViewCancelEventArgs e) {
1274 if (!_treeNodeFirst) {
1275 _treeNodeFirst = true;
1276 e.Node.BackColor = Color.Silver;
1277 }
1278 }
1346 void TreeNode_AfterCheck(object sender, TreeViewEventArgs e) {
1347 if (e.Node.Checked) {
1348 foreach (TreeNode sub in e.Node.Nodes) {
1349 sub.Checked = e.Node.Checked;
1350 }
1351 }
1352 if (e.Node.BackColor == Color.Silver) {
1353 e.Node.BackColor = Color.Empty;
1354 RunButton.Enabled = IsANodeChecked();
1355 _treeNodeFirst = false;
1356 }
1357 }
1429 static bool IsANodeChecked(TreeNode node) {
1430 if (node.Checked) return true;
1431 foreach (TreeNode sub in node.Nodes) {
1432 if (IsANodeChecked(sub)) {
1433 return true;
1434 }
1435 }
1436 return false;
1437 }
This seems to be the best way (that I can see right now) to ensure that IsANodeChecked(TreeNode) is only run once when a group of nodes is selected all at once.
I do, however, really like Jimmy Hoffa's idea of using a count, though. I will probably add that to my code.
Thanks to all!
~Joe

Categories

Resources