how to find dynamically created CheckBox checked in wpf - c#

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;
}

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

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);
}

check parents of child

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)
{
}
}

How to find element in visual tree? wp7

How I can find element that contains in App.xaml, grid with name "audioPanel"?
I tried:
Grid found = this.FindChild<Grid>(^*I can't find anything suitable*^, "audioPanel");
How can I find WPF controls by name or type?
UPD: App.xaml http://pastebin.com/KfWbjMV8
UPDATE: You need a combination of both my answer and H.B.'s answer. Use the version of FindChild below, and change your call to FindChild to look like
var grid = FindChild<Grid>(Application.Current.RootVisual, "audioPanel");
Since you're styling the phone application frame, the "control on which it is applied" from H.B.'s comment is pretty likely to be the RootVisual (there may be exceptions to this, I'm not sure).
Also, I'm assuming that the "..." parts of your App.xaml in pastebin have a ContentPresenter in there somewhere, otherwise I don't think your style will work.
END UPDATE
If you're using the accepted answer in the question you linked to (WPF ways to find controls) and your 'audioPanel' grid is nested inside of another grid, then you still won't find it - there's an error in that code. Here's an updated version that will work even if the control is nested:
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++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
var 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;
}
// Need this in case the element we want is nested
// in another element of the same type
foundChild = FindChild<T>(child, childName);
}
else
{
// child element found.
foundChild = (T) child;
break;
}
}
return foundChild;
}
}
If it is in App.xaml i would assume it to be part of a resource in Application.Resources, as resources that are not used anywhere are not in the visual tree this won't do.
If this is true you can try getting the root of the object from the resources and search from there, e.g.
var root = Application.Current.Resources["MyKey"] as FrameworkElement;
Grid found = this.FindChild<Grid>(root, "audioPanel");
just for completeness, the version of E. Z. Hart has a bug, as found sub childs are overwritten. here is a working version
public static T FindChild<T>(this DependencyObject parent, string childName = null) where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null)
return null;
T foundChild = null;
var childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; foundChild == null && i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
var childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
}
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;
}
else
{
// Need this in case the element we want is nested
// in another element of the same type
foundChild = FindChild<T>(child, childName);
}
}
else
{
// child element found.
foundChild = (T)child;
}
}
return foundChild;
}

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