check parents of child - c#

I have an asp.net treeview (acting as a remote file and folder browser). When a node is selected all child nodes are automatically selected. This works fine (c# code below).
When any child is checked/unchecked I want all related parents to be checked/unchecked as well. I cannot figure this out. I want to use c# to do this.
-item1
------child1
------child2
--child2.1
--child2.2
------child3
Example 1 - if child 2.2 had its checkbox checked then child 2 and item1 will be checked automatically using c# code behind
Example 2 - if item1, child 2 , child 2.1 and child 2.2 were checked and if the user were to uncheck child 2.2 then item1, child 2 would remain checked as child 2.1 is still checked
thanks
Damo
below is my code that checks all children of a checked item and works fine.
/// <summary>
/// Checks or unchecks child nodes when a parent node is checked or unchecked.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void OnTreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
{
// Determine if checked Node is a root node.
if (e.Node.ChildNodes.Count > 0)
{
// Check or uncheck all of the child nodes based on status of parent node.
if (e.Node.Checked)
ChangeChecked(e.Node, true);
else
ChangeChecked(e.Node, false);
}
}
/// <summary>
/// Recursively checks or unchecks all child nodes for a given TreeNode.
/// </summary>
/// <param name="node">TreeNode to check or uncheck.</param>
/// <param name="check">Desired value of TreeNode.Checked.</param>
private void ChangeChecked(TreeNode node, bool check)
{
// "Queue" up child nodes to be checked or unchecked.
if (node.ChildNodes.Count > 0)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
ChangeChecked(node.ChildNodes[i], check);
}
node.Checked = check;
}

I figured this out
I have 2 functions as follows . The first checks all the children and the second checks all the parents.
Hope this helps someone.
Damo
ChangeCheckedChildren(e.Node, e.Node.Checked);
ChangeCheckedParents(e.Node, e.Node.Checked);
/// <summary>
/// Recursively checks or unchecks all child nodes for a given TreeNode.
/// </summary>
/// <param name="node">TreeNode to check or uncheck.</param>
/// <param name="check">Desired value of TreeNode.Checked.</param>
private void ChangeCheckedChildren(TreeNode node, bool check)
{
try
{
// "Queue" up child nodes to be checked or unchecked.
if (node.ChildNodes.Count > 0)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
ChangeCheckedChildren(node.ChildNodes[i], check);
}
node.Checked = check;
}
catch (Exception ex)
{
}
}
/// <summary>
/// Recursively checks or unchecks all parent nodes for a given TreeNode.
/// </summary>
/// <param name="node">TreeNode to check or uncheck.</param>
/// <param name="check">Desired value of TreeNode.Checked.</param>
private void ChangeCheckedParents(TreeNode node, bool check)
{
try
{
if (node.Parent == null) // if we are at the root node
{
if (node.ChildNodes.Count > 0)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].Checked == true)
{
node.Checked = true;
return;
}
}
node.Checked = false;
}
else
{
node.Checked = check;
}
}
else
{
// Check all parents if the user is checking
if (check == true)
{
node.Checked = check;
ChangeCheckedParents(node.Parent, check);
}
else
{
// Do not uncheck a parent if any of its other children or their children are checked
if (node.ChildNodes.Count > 0)
{
// Default to not check and check if required
node.Checked = false;
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].Checked == true)
{
node.Checked = true;
}
}
ChangeCheckedParents(node.Parent, check);
}
else
{
node.Checked = check;
ChangeCheckedParents(node.Parent, check);
}
}
}
}
catch (Exception ex)
{
}
}

Related

C# TreeView selected node loosing Focus after moving that node

I am working with Windows Form project. I am using VS2013 and .net version is 4.5. i do not have very high knowledge in .Net.
I want to up down any node of my tree view which was possible from this post https://stackoverflow.com/a/2204091/14326209
Here is the code
/// <summary>
/// Move Selected Node Up in TreeNode Collection
/// </summary>
/// <param name="node"></param>
public static void MoveUp(this TreeNode node)
{
TreeNode parent = node.Parent;
TreeView view = node.TreeView;
if (parent != null)
{
int index = parent.Nodes.IndexOf(node);
if (index > 0)
{
parent.Nodes.RemoveAt(index);
parent.Nodes.Insert(index - 1, node);
node.Text = node.Text;
}
}
else if (node.TreeView.Nodes.Contains(node)) //root node
{
int index = view.Nodes.IndexOf(node);
if (index > 0)
{
view.Nodes.RemoveAt(index);
view.Nodes.Insert(index - 1, node);
node.Text = node.Text;
}
}
//view.Focus();
//view.SelectedNode = node;
//node.EnsureVisible();
}
/// <summary>
/// Move Selected Node Down in TreeNode Collection
/// </summary>
/// <param name="node"></param>
public static void MoveDown(this TreeNode node)
{
TreeNode parent = node.Parent;
TreeView view = node.TreeView;
if (parent != null)
{
int index = parent.Nodes.IndexOf(node);
if (index < parent.Nodes.Count - 1)
{
parent.Nodes.RemoveAt(index);
parent.Nodes.Insert(index + 1, node);
node.Text = node.Text;
}
}
else if (view != null && view.Nodes.Contains(node)) //root node
{
int index = view.Nodes.IndexOf(node);
if (index < view.Nodes.Count - 1)
{
view.Nodes.RemoveAt(index);
view.Nodes.Insert(index + 1, node);
node.Text = node.Text;
}
}
//view.Focus();
//view.SelectedNode = node;
//node.EnsureVisible();
}
private void tvCsmTuner_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
tvCsmTuner.SelectedNode.MoveUp();
}
else if (e.KeyCode == Keys.Down)
{
tvCsmTuner.SelectedNode.MoveDown();
}
label3.Focus();
}
when i call Node.MoveDown() and Node.MoveUp() then Node is getting perfectly moving but selection from Selected node going to different node after node moved. i want selection should persist on selected node after moving the Node.
So please guide me what changes need to add in the above code as a result selection on selected node should not go to any node.
I tried this to persist node selection but did not work.
view.SelectedNode = node;
Looking for suggestion. thanks

how to find dynamically created CheckBox checked in wpf

I created Check Box dynamically inside a wrap panel in wpf. How to find the checked check box in code behind.
If you want a more compact not reusable and specialized version..
WrapPanel wp = new WrapPanel();
for (int i = 0; i < 10; i++)
{
CheckBox chb = new CheckBox();
chb.Name = string.Format("Id{0}", i);
wp.Children.Add(chb);
}
foreach (CheckBox el in wp.Children)
{
if (el.Name == "Id3")
{
return el;
}
}
/// <summary>
/// Finds a Child of a given item in the visual tree.
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found,
/// a null parent is being returned.</returns>
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
If you are looking for the text of the selected checkbox do somthing like thes:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
string a =checkBox1.Text;
}

Loop an UIElement variable name

I try to loop the names of my food objects in an WPF application.
I want the following names of the foodelement: food0, food1, foot2 ...
for (int i = 0; i < foods.Count; i++)
{
System.Windows.UIElement foodelement = "food" + i; // ERROR here
Canvas.SetLeft(foodelement, foods[i].Position.X);
}
I get the error:
Cannot implicitly convert type string to System.Windows.UIElement
This may help you
System.Windows.UIElement foodelement = (System.Windows.UIElement)YourContainer.FindName("food" + i);
Where YourContainer is the the container(grid/canvas/stack panel/) that holds the UIElements.
Or else you can use the following:
System.Windows.UIElement foodelement = UIHelper.FindChild<System.Windows.UIElement>(Application.Current.MainWindow, "food" + i);
I think Following code will help you
/// <summary>
/// Finds a Child of a given item in the visual tree.
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found,
/// a null parent is being returned.</returns>
public static T FindChild<T>(DependencyObject parent, string childName)
where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null) return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null) break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
And use this method
for (int i = 0; i < foods.Count; i++)
{
System.Windows.UIElement ui = FindChild<Button>(Application.Current.MainWindow, "food" + i);
}

Append Text to Richtextbox on Multiple Checked Node in C#

I am working on Windows Form Application C#, When i check few treeview Nodes and on Button Click Event, Text corresponding to each Treenode will be Append to richtextbox.
I had done similar thing while Select Treenode, Ex:
if(treeView1.SelectedNode.Name == "First Node")
this.richTextBox1.SelectedText = Firstline;
elseif(treeView1.SelectedNode.Name == "Second Node")
this.richTextBox1.SelectedText = Other Text;
But i need to do similar activity for Multiple Checked Node from my treeview (On Button press event).
Please help me
as your question is not clear . assuming
you have winform with treeView1Control
//populating treeView with dummy data
private void Form2_Load(object sender, EventArgs e)
{
//set the check box true
treeView1.CheckBoxes = true;
TreeNode treeNode = new TreeNode("Windows");
treeView1.Nodes.Add(treeNode);
//
// Another node following the first node.
//
treeNode = new TreeNode("Linux");
treeView1.Nodes.Add(treeNode);
//
// Create two child nodes and put them in an array.
// ... Add the third node, and specify these as its children.
//
TreeNode node2 = new TreeNode("C#");
TreeNode node3 = new TreeNode("VB.NET");
TreeNode[] array = new TreeNode[] { node2, node3 };
//
// Final node.
//
treeNode = new TreeNode("Dot Net Perls", array);
treeView1.Nodes.Add(treeNode);
}
private void button3_Click(object sender, EventArgs e)
{
string text = traverseTreeAngGetName(treeView1.Nodes);
this.richTextBox1.SelectedText = text;
}
/// <summary>
/// it will traverse all the tree Node from 1 to N Level. if Node is Checked then get
/// the checked node name.
/// </summary>
/// <param name="tr"></param>
/// <returns></returns>
public static string traverseTreeAngGetName(TreeNodeCollection tr){
string str = "";
foreach (TreeNode node in tr) {
if (node.Checked) {
//here you can append any text on the base of current
str += node.Text + " - " ;
}
str += traverseTreeAngGetName(node.Nodes);
}
return str;
}

How can move up and move down selected item programmatically in treeview in c#? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
i have one treeview and 2 button
i want when click on UP_button, above Node selected if i am click on DOWN_button then selection should be go down
There are some nice built in properties of the node that you can use, so for up you would use:
TreeView.SelectedNode = TreeView.SelectedNode.PrevNode;
and for down:
TreeView.SelectedNode = TreeView.SelectedNode.NextNode;
From MSDN Documentation:
private void SelectNode(TreeNode node)
{
if(node.IsSelected)
{
// Determine which TreeNode to select.
switch(myComboBox.Text)
{
case "Previous":
node.TreeView.SelectedNode = node.PrevNode;
break;
case "PreviousVisible":
node.TreeView.SelectedNode = node.PrevVisibleNode;
break;
case "Next":
node.TreeView.SelectedNode = node.NextNode;
break;
case "NextVisible":
node.TreeView.SelectedNode = node.NextVisibleNode;
break;
case "First":
node.TreeView.SelectedNode = node.FirstNode;
break;
case "Last":
node.TreeView.SelectedNode = node.LastNode;
break;
}
}
node.TreeView.Focus();
}
EDIT
You'd of course use the cases for "Previous" and "Next" or "PreviousVisible" and "NextVisible" in your button click handlers. This code assumes that you select the "action" from a combo box and push a button.
EDIT 2
Just in case you are trying to move the nodes up and down (not the selection), you can use something like the following:
TreeNode sourceNode = treeView.SelectedNode;
if (sourceNode.Parent == null)
{
return;
}
treeView.Nodes.Remove(sourceNode);
treeView.Nodes.Insert(sourceNode.Index + 1, sourceNode);
This would move the current node one down. Please note that you have to write some more code to handle some special cases (e.g. what happens with the first node? Does it work on all levels of the tree?), but basically that's what I'd try.
try this for UP:
private void btnUP_Click(object sender, EventArgs e)
{
var tn = tv.SelectedNode;
if(tn==null) return;
var idx = tn.Index;
txt.Text = "Node: " + idx;
var par = tn.Parent;
if(par==null) return;
par.Nodes.Remove(tn);
if (idx > 0)
{
par.Nodes.Insert(tn.Index - 1, tn);
return;
}
//if you want to move int its parent's parent [grand parent :) ]
if (par.Parent!=null)
par.Parent.Nodes.Add(tn);
}
For ASP.NET Treeview:
/// <summary>
/// MoveComponentUpLinkButton_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MoveComponentUpLinkButton_Click(object sender, EventArgs e)
{
// Get the selected node
TreeNode sourceNode = this.MyTreeview.SelectedNode;
if (sourceNode != null)
{
// Get the selected node's parent
TreeNode parentNode = this.MyTreeview.SelectedNode.Parent;
if (parentNode != null)
{
int index = -1;
// For each node in selected nodes parent
for (int j = 0; j < parentNode.ChildNodes.Count; j++)
{
// If we found the selected node
if (sourceNode == parentNode.ChildNodes[j])
{
// save index
index = j;
break;
}
}
// If node is not already at top of list
if (index > 0)
{
// Move it up
parentNode.ChildNodes.RemoveAt(index);
parentNode.ChildNodes.AddAt(index - 1, sourceNode);
sourceNode.Selected = true;
}
}
}
}
/// <summary>
/// MoveComponentDownLinkButton_Click
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void MoveComponentDownLinkButton_Click(object sender, EventArgs e)
{
// Get the selected node
TreeNode sourceNode = this.MyTreeview.SelectedNode;
if (sourceNode != null)
{
// Get the selected node's parent
TreeNode parentNode = this.MyTreeview.SelectedNode.Parent;
if (parentNode != null)
{
int index = -1;
// For each node in selected nodes parent
for (int j = 0; j < parentNode.ChildNodes.Count; j++)
{
// If we found the selected node
if (sourceNode == parentNode.ChildNodes[j])
{
// save index
index = j;
break;
}
}
// If node is not already at botton of list
if (index < parentNode.ChildNodes.Count - 1)
{
// Move it down
parentNode.ChildNodes.RemoveAt(index);
parentNode.ChildNodes.AddAt(index + 1, sourceNode);
sourceNode.Selected = true;
}
}
}
}
my problem solved.
thanx for answers
private void button1_Click(object sender, EventArgs e)
{
TreeNode node = new TreeNode();
node = treeView1.SelectedNode;
treeView1.SelectedNode = node.NextVisibleNode;
node.TreeView.Focus();
}

Categories