Search code examples
c#treeviewtreenodechild-nodes

C# TreeView, event when childnode is selected


I have a question concerning TreeViews and their Nodes in C#.

What I currently try to do. I have a TreeView and next to it a TableLayoutPanel. When I click of the Nodes, I want to call a specific Method and display the Data in the TableLayoutPanel. Displaying the data works fine, but my problem is that I dont know exactly how to determine what Node/ChildNode has been selected.

I have a TreeView that looks like this

Root1
     R1Child1
     R1Child2
Root2
     R2Child1
     R2Child2
Root3
     R3Child1
     R3Child2

I currently handle this by an AfterSelect Method and just check the selected Node for the Text.

private void treeHardware_AfterSelect(object sender, TreeViewEventArgs e)
{

        if (e.Node.Text == SysInfo.CPU.Name)
        {
            deleteRows();
            initFixedRows();
            updateTableCPU();
        }
        else if (e.Node.Text == ramNameIdent)
        {
            deleteRows();
            initFixedRows();
            updateTableRAM(e.Node.Index);
        }
        else if (e.Node.Text == "Memory")
        {
            deleteRows();
            initFixedRows();
            loadRAMDetails(0);
            loadRAMOverview();
        }
        else if( e.Node.Text == "Mainboard")
        {
            deleteRows();
            initFixedRows();
            updateTableMainboard();
        }
        else
        {
            Console.WriteLine("ERROR");
        }
}

In my Opinion this is a very unpractical way to check what Node has been clicked, because it just checks Strings, and it isnt very effective..

Next Problem, for Memory Node. I display all installed Physical Memories and add each of them as a ChildNode. Now when I click one of them, it should display the Data of the selected Memory in my TableLayoutPanel. But It always just shows the "last" one.

Hope hat you understand what I mean... If not, just ask for more Information :-)

Cheers, Consti


Solution

  • Use the Tag Property , put an ID in the tag property that is unique for every node