Search code examples
c#.netcheckboxtreeviewunique

TreeView checkboxes to work as individual & separate checkboxes in C# .Net


I need to have 7 nodes and inside each nearly 30-40 child nodes. Each child-node need to have a 'function body' of it's own, like we can have for a normal single checkbox while working in Form1 in C#. so that I can have freedom to assign it unique task (like fetching unique data, string concatenation and also parsing values to another function). I need to have access to each checkbox basically. What so far I tried after creating tree-list was (showing just few lines for simplicity):

treeView1.Nodes.Add("Session");
treeView1.Nodes.Add("Reset");

treeView1.Nodes[0].Nodes.Add("Extended Start");
treeView1.Nodes[1].Nodes.Add("Hard Reset");
treeView1.Nodes[2].Nodes.Add("EOL Mode State Read");
treeView1.Nodes[2].Nodes.Add("Current Err Tracer Read");
treeView1.Nodes[2].Nodes.Add("Read Odometer value from Bus Read");

This generates tree-view GUI like I need but accessing check-boxes is my main question!

Thanks


Solution

  • You may define your custom tree node with a delegate property containing some code to perform your tasks, e.g.:

    class ActionNode : TreeNode
    {
        public Action Action { get; }
        public ActionNode(string text, Action action)
            : base(text)
        {
            Action = action;
        }
    }
    

    Then add instances of this class as sub-nodes assigning concrete task code to each instance. For example:

    treeView1.Nodes[0].Nodes.Add(new ActionNode("Extended Start",
        () => { MessageBox.Show("Extended Start"); }));
    treeView1.Nodes[1].Nodes.Add(new ActionNode("Hard Reset",
        () => { MessageBox.Show("Hard Reset"); }));
    treeView1.Nodes[2].Nodes.Add(new ActionNode("EOL Mode State Read",
        () => { MessageBox.Show("EOL Mode State Read"); }));
    treeView1.Nodes[2].Nodes.Add(new ActionNode("Current Err Tracer Read",
        () => { MessageBox.Show("Current Err Tracer Read"); }));
    treeView1.Nodes[2].Nodes.Add(new ActionNode("Read Odometer value from Bus Read",
        () => { MessageBox.Show("Read Odometer value from Bus Read"); }));
    

    (NB: the top level nodes implementation may be left as is.)

    Then you can use your nodes to access unique task code like this:

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {
        var actionNode = e.Node as ActionNode;
        if (actionNode != null)
            actionNode.Action();
    }