Zaryab Waseem Zaryab Waseem - 15 days ago 6
C# Question

how to get the index of current selected node from treeview in c#

I'm working on a form application in c# that includes TreeView in it. What I want to do is to attach a panel to each node so whenever user clicks on a node the panel will be updated according to the node selected.

The problem I'm facing is that when I select a node, the application does nothing but when I select another node then the application shows the content related to previously selected node. Means that App is always getting content related to last selected node not the current one. For Example If I'll select "Text" node, the label will show nothing and after that If I'll select some other node like "Appearance" the label will show "Text" which was the last selected node.

Following here is the image of my Form that contains TreeView.

Form Cotaining TreeView
For testing purpose I'm just storing the selected node's value in my label's text
Here's the code.

public partial class TextEditor_Preferences : Form
{
public TextEditor_Preferences()
{
InitializeComponent();

}
List<Panel> myPanels = new List<Panel>(); //Ignore this line of code !

private void SideBar_MouseClick(object sender, MouseEventArgs e)
{
label1.Text = SideBar.SelectedNode.ToString();
}
}


Can anobody suggest me a method?

If I'm missing something or question is not valid, Please let me know explicitly. Thanks

Answer

TreeView control has the AfterSelect event you should write your code in that handler.

public YourForm()
{
    InitializeComponent();
    treeView.AfterSelect += TreeViewAfterSelect;
}

private void TreeViewAfterSelect(object sender, TreeViewEventArgs e)
{
    string nodeText = treeView.SelectedNode.Text;

    // Update the panel here accordingly
}
Comments