Getting the SelectedIndex of a child node in a TreeView - c#

I am currently working on a wpf project in C#.
I have a treeview created that has parent nodes with childen nodes inside of it.
I was wondering if there was a way to get the index of the child node the user clicked on. (Simmilar to ".SelectedIndex" when using comboboxes)
I have tried Various ways such as:
int val =TreeView.SelectedItemProperty.GlobalIndex;
and
fileInput.IndexOf(treeView1.SelectedItem);
But they dont seem to work.
Any suggestions or comments are greatly appreciated.
Thanks

may you have to loop over tree nodes to get the index of SelectedItem. you can do that using OnItemSelected event.for ex.
Int32 selectedNodeIndex=-1;
private void TreeView1_OnItemSelected(Object sender,RoutedEventArgs e)
{
Int32 index=0;
foreach(var _item in TreeView1.Items)
{
if(_item==TreeView1.SelectedItem)
{
selectedNodeIndex = index;
break;
}
index++;
}
}

This post discusses exactly what you need I think. About handling the SelectedNodeChanged event and also a custom piece of code for an event that fires when the currently selected node is clicked...because then the SelectedNodeChanged doesn't fire (the selected node doesn't change actually). Good luck!

Related

Referencing the TreeView from other TreeViews

I have a window form that has a control treeViewMain and in the code I have a list of treeViews that has variable number of treeViews. I want the treeViewMain to show anyone of the treeView from the list.
treeViewMain=treeViews[0];
but the form is not showing the tree. Also I have thoroughly checked the treeViews in the list, they are populating correctly.
Apparently simple assigning does not work. According to this post it seems that the parent of a TreeViewNode has to be unique and there by the "fruit" can only sit at one tree.
One workaround could be to set the parent property of the TreeView in your list to the treeViewMain:
treeViews[0].Parent = treeViewMain;
this will put the treeview from the list as a child inside treeViewMain. If you want to change that and load the next item from your list you need to make sure that the previously loaded item's parent property is set to null before assigning a new parent like in this example:
private int count = 0;
private void button_ChooseTreeView_Click(object sender, EventArgs e)
{
if (count > 0)
{
treeViews[count -1].Parent = null;
}
treeViews[count].Parent = treeViewMain;
count++;
}
The other possibility would be to clone each node and populate the treeViewMain each time you want to update the list items to the display

How to maintain checkstate of items in Devexpress Virtual Treeview?

I have a Treeview created in virtual mode which have 4 levels of nodes and at the page load the root element and first level elements are loaded and rest will be loaded based on dynamically using treeFolderList_VirtualModeCreateChildren event.
This is what I have so far
protected void treeFolderList_VirtualModeCreateChildren(object source, TreeViewVirtualModeCreateChildrenEventArgs e)
{
List<TreeViewVirtualNode> children = new List<TreeViewVirtualNode>();
if (e.NodeName == null)
{
AppendChildNode(children, "root", "All Domains", false);
}
else
{
if (e.NodeName.Contains("root"))
{
PopulateChildNodes(false, children);
}
else
{
if (!(e.NodeName.StartsWith("u_")))
{
PopulateUserChildNodes(false, children, GetDomainBase(e.NodeName), e.NodeName);
}
else
{
TreeViewVirtualNode tvNode = (TreeViewVirtualNode)treeFolderList.Nodes.FindByName(e.NodeName);
TreeViewVirtualNode tvNodeParent = (TreeViewVirtualNode)tvNode.Parent;
string tvParentNodeName = tvNodeParent.Name;
PopulateUserChildNodes(true, children, GetDomainBase(tvParentNodeName), e.NodeName);
}
}
}
e.Children = children;
}
This work as expected and it creates the children elements when expanding nodes respectively. My problem is I have check boxes for each node and I need to be able to save the Treeview in a way when I reload/redirect to the page it would reflect the nodes I have selected.
Is there a way to achieve this?
There are several ways to try to achieve this:
Configure ASPxTreeList.SettingsCookies element (probably the easiest solution), in particular the StoreSelection attribute:
<dvx:ASPxTreeList ... >
...
<SettingsCookies Enabled="true" StoreSelection="true" />
...
</dvx:ASPxTreeList>
If SettingsCookies doesn't work try saving and restoring the TreeList layout manually using ASPxTreeList.ClientLayout event. Define the event handler first:
<dvx:ASPxTreeList OnClientLayout="dvxTreeList_ClientLayout"... >
...
</dvx:ASPxTreeList>
and follow the example in the doc to handle this event. This way ASPxTreeView as well as the ASPxGridView provide the node/column format data in the e.LayoutData string which can be saved to DB and then restored back.
Store the TreeView selected node keys in Session and restore them using callbacks:
Example: ASPxTreeList - How to store the selection between requests
I personally would not rely on cookies and would try methods #2 and #3 first. #2 has been working nicely for me with ASPxGridView and #3 we use in a complex ASPxTreeView setup which also tracks the selection of hidden nodes.
I hope the examples in the linked docs should be easy enough for you to copy and modify. If not, comment what is not working for you.
HTH

How can I set an event handler for all TreeViewItems in code?

I want to subscribe to the TreeViewItem.Expanded event on TreeView level. In xaml, this is easy: OnExpanded event for any item in a treeview
However, I subclassed TreeView and therefore do not have a xaml file. What can I do in C# code to achieve the same?
Just walk recursive through the node and add your Eventhandler
void AddHandler(Node node) {
foreach(varnode in node.Nodes) {
node.OnExpanded += nodeExpandedEvent;
if(node.Nodes.Count > 0) {
this.AddHandler(node, nodeChecked);
}
}
}
Or use the solution Ash provided
TreeView.AddHandler(TreeViewItem.ExpandedEvent, (RoutedEventHandler)TreeViewItem_Expanded);

Focusing TreeViewElement after Refresh

I have a Problem with focusing an TreeViewItem.
I have a (little bit optimated) TreeView and refreshing the content.
Visually the selected Item stays selected but logically it isn't. The Focus-Check at the beginning and at the end are not the same, but in my opinion they should.
Here is my Code (with all non-working refocusing things):
private void Refresh(string selectedContent)
{
//Check out the focused element
//Returns "System.Windows.Controls.TreeViewItem Header:<my selectedContent-Value>; Items.Count:0"
MessageBox.Show(Keyboard.FocusedElement.ToString());
var currentFocus = Keyboard.FocusedElement;
tv.Refresh(); //this refreshes the treeview
//Not working
Keyboard.Focus(currentFocus);
//Not working
DependencyObject focusScope = FocusManager.GetFocusScope(currentFocus);
FocusManager.SetFocusedElement(focusScope, currentFocus);
//also not working
currentFocus.Focus();
//not working
Keyboard.Focus(tv.TryFindNode(selectedContent)); //TryFindNode searches the node in the TreeView and returns it
//not working
tv.TryFindNode(selectedContent).Focus();
//Check out the focused element
//returns "TreeViewTesting.TreeViewTesting" (my class where I'm testing this issue)
MessageBox.Show(Keyboard.FocusedElement.ToString());
}
What I don't understand is, that this works:
private void Refresh(string selectedContent)
{
//Check out the focused element
//Returns "System.Windows.Controls.TreeViewItem Header:<my selectedContent-Value>; Items.Count:0"
MessageBox.Show(Keyboard.FocusedElement.ToString());
tv.Refresh(); //this refreshes the treeview
MessageBox.Show("I'm just a Message to show a messagebox");
tv.TryFindNode(selectedContent).Focus();
//Check out the focused element
//Returns "System.Windows.Controls.TreeViewItem Header:<my selectedContent-Value>; Items.Count:0"
MessageBox.Show(Keyboard.FocusedElement.ToString());
}
So, how do I that, what the Dummy-Messagebox is doing with the focus?
Anyone has an Idea?
I have an application that manipulates other controls after selecting a TreeNode in a TreeView. When the process is done, the TreeNode is still selected but the TreeView has lost focus.
Based on Hunv's approach in their comments above, I found the following to produce the desired result (which is TreeView focused, TreeNode selected):
private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
{
ProcessMySelection();
// give the app a chance to 'recover' and keep focus on the TreeView
// i don't understand why this works -- is there a better way?
Application.DoEvents()
}

how to get xml data to listbox

ive got a problem with getting my data from a xml file to an listbox.
this is the data i want to get in my listbox:
<gjester>
<gjest>
<id>test</id>
<fornanv>test</fornanv>
<etternavn>test</etternavn>
<adresse>test</adresse>
<telefonnr>test</telefonnr>
</gjest>
</gjester>
and i created a listbox in my gui. But i don't know what to write in my code.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
I don't know what to write here
}
There are approximately a bazillion ways to add items from an XML file to your listbox but a good place to start would be the MSDN documentation for the XMLTextReader class and the ListBox.Items.Add() method.
Also - you will probably want to do this somewhere other than the SelectedIndexChanged event on the listbox. For learning purposes, try it on a button click.
Good luck - and after looking into the above I'm sure someone will help you if you haven't figured it out.
This is .NET 4.0 (VS2010 C#) and is completely untested but may give you a start....
private void FillListBoxWithThingsIWantToSelect()
{
XDocument ListBoxOptions = XDocument.Load(Filename);
foreach (XElement element in ListBoxOptions.Root.Elements())
{
if (element.Name.LocalName.Contains("gjester"))
{
foreach (XElement subelement in element.Elements())
{
if (subelement.Name.LocalName.Contains("gjest"))
{
// What do you want to add? The Attribute? Element value
listbox1.Items.Add(element.Value.ToString());
}
}
}
}
}
Would help if you listed your platform and what you want in the listbox.
You want to call this from your constructor.
Can use dictionary object to bind the data from XML to Listbox.
var dic = (from order in ds.Tables[0].AsEnumerable()
select new
{
UserView = order.Field<String>("Value"),
DevView = order.Field<String>("id")
}).AsEnumerable().ToDictionary(k => k.DevView, v => v.UserView);
Click here for reference

Categories

Resources