bind editable tree view with specific field from json

Surya P Singh 21 Reputation points
2022-03-29T23:52:41.61+00:00

I have a json like below
{
"Name": "General Health",
"Version": "1.2",
"abcd": "xy1z",
"NameSpace": "testing",
"Sections": [
{
"Name": "Height",
"Nodes": [
{
"Actions": [],
"Name": "4604",
"Text": "What is your exact height in cms ?",
"HelpText": null,
"Tag": "Whatisyourexactheightincms4604",
"IsRoot": true,
"IsOptional": false
},
{
"Actions": [],
"Name": "4605",
"Text": "What is your exact height in feet and inches ?",
"HelpText": null,
"Tag": "Whatisyourexactheightinfeetandinches4605",
"IsRoot": true,
"IsOptional": false
}
],
"IsRoot": true
},
{
"Name": "weight",
"Nodes": [
{
"Actions": [],
"Name": "5604",
"Text": "What is your exact weight in pounds ?",
"HelpText": null,
"Tag": "Whatisyourexactweightinpounds5604",
"IsRoot": true,
"IsOptional": false
},
{
"Actions": [],
"Name": "5605",
"Text": "What is your exact weight in kgs ?",
"HelpText": null,
"Tag": "Whatisyourexactweightinkgs5605",
"IsRoot": true,
"IsOptional": false
}
],
"IsRoot": true
}
]
}
here i want to bind this josn to a tree view (Editable meaning I can add /delete/update any tree node). I need to bind specific fields from json like section's name and node's text. so treeview would look like below

{
"Name": "General Health",
"Version": "1.2",
"abcd": "xy1z",
"NameSpace": "testing",
"Question": [
{ "Name": "height",
"SubQuestion": [
{
"Text": "What is your exact height in cms ?"
},
{
"Text": "What is your exact height in feet and inches ?"
}
]

},
{
  "Name": "weight",
  "SubQuestion": [
    {          
      "Text": "What is your exact weight in pounds ?"         
    },
    {         
      "Text": "What is your exact weight in kgs ?"          
    }
  ]

}

]
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,528 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,490 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,136 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,476 Reputation points Microsoft Vendor
    2022-03-30T07:56:25.733+00:00

    @Surya P Singh , Welcome to Microsoft Q&A, you could try the following steps to make an editable treeview.

    First, Please install nuget-package Newtonsoft.Json.

    Second, you could try to add a ContextMenu to the node.

    Finally, Please refer to the following code to get what you wanted.

        public partial class Form1 : Form  
    {  
        string clickedNode;  
        MenuItem addMenuItem = new MenuItem("Add");  
        MenuItem deleteMenuItem = new MenuItem("delete");  
        MenuItem updateMenuItem = new MenuItem("update");  
        ContextMenu mnu = new ContextMenu();  
        public Form1()  
        {  
            InitializeComponent();  
            mnu.MenuItems.Add(addMenuItem);  
            mnu.MenuItems.Add(deleteMenuItem);  
            mnu.MenuItems.Add(updateMenuItem);  
            addMenuItem.Click += AddMenuItem_Click;  
            deleteMenuItem.Click += DeleteMenuItem_Click;  
            updateMenuItem.Click += UpdateMenuItem_Click;  
        }  
        private void AddMenuItem_Click(object sender, EventArgs e)  
        {  
            TreeNode newNode = new TreeNode("node1");  
            treeView1.SelectedNode.Nodes.Add(newNode);  
        }  
    
        private void UpdateMenuItem_Click(object sender, EventArgs e)  
        {  
            treeView1.LabelEdit = true;  
            treeView1.SelectedNode.BeginEdit();  
        }  
    
        private void DeleteMenuItem_Click(object sender, EventArgs e)  
        {  
            treeView1.SelectedNode.Remove();  
        }  
        TreeNode node = new TreeNode();  
        private void Form1_Load(object sender, EventArgs e)  
        {  
            string source = File.ReadAllText(@"C:\Users\username\Desktop\1.json");  
            dynamic data = JObject.Parse(source);  
            node.Text = "";  
            treeView1.Nodes.Add(node);  
            var Name = data.Name;  
            Addnode("Name", Name);  
            var Version = data.Version;  
            Addnode("Version", Version);  
            var abcd = data.abcd;  
            Addnode("abcd", abcd);  
            var NameSpace= data.NameSpace;  
            Addnode("NameSpace", NameSpace);  
            TreeNode question = new TreeNode();  
            question.Text = "Question";  
            node.Nodes.Add(question);  
            var height = data.Sections[0].Name;  
            TreeNode heightnode=new TreeNode();  
            heightnode.Text = "Name";  
            TreeNode heightnodev = new TreeNode();  
            heightnodev.Text = height;  
            question.Nodes.Add(heightnode);  
            heightnode.Nodes.Add(heightnodev);  
            TreeNode SubQuestion = new TreeNode();  
            SubQuestion.Text = "SubQuestion";  
            question.Nodes.Add(SubQuestion);  
            TreeNode textnode=new TreeNode();  
            textnode.Text = "Text";  
            SubQuestion.Nodes.Add(textnode);  
            TreeNode text=new TreeNode();  
            text.Text = data.Sections[0].Nodes[0].Text;  
            textnode.Nodes.Add(text);  
            TreeNode textnode1 = new TreeNode();  
            textnode1.Text = "Text";  
            SubQuestion.Nodes.Add(textnode1);  
            TreeNode text1 = new TreeNode();  
            text1.Text = data.Sections[0].Nodes[1].Text;  
            textnode1.Nodes.Add(text1);  
    
            treeView1.LabelEdit = true;  
    
            foreach (TreeNode n in treeView1.Nodes)  
            {  
                PrintNonRecursive(n);  
            }  
        }  
    
        private void PrintNonRecursive(TreeNode treeNode)  
        {  
            if (treeNode != null)  
            {  
                //Using a queue to store and process each node in the TreeView  
                Queue<TreeNode> staging = new Queue<TreeNode>();  
                staging.Enqueue(treeNode);  
    
                while (staging.Count > 0)  
                {  
                    treeNode = staging.Dequeue();  
    
                    treeNode.Tag = treeNode.Text;  
    
                    foreach (TreeNode node in treeNode.Nodes)  
                    {  
                        staging.Enqueue(node);  
                    }  
                }  
            }  
        }  
        private void Addnode(string Name,JToken token)  
        {  
    
            TreeNode namenode = new TreeNode();  
            namenode.Text = Name;  
            TreeNode namevnode = new TreeNode();  
            namevnode.Text = token.ToString();  
    
            namenode.Nodes.Add(namevnode);  
            node.Nodes.Add(namenode);  
        }  
       
    
    
    
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)  
        {  
            if (e.Button == MouseButtons.Right)  
            {  
                clickedNode = e.Node.Name;  
                mnu.Show(treeView1, e.Location);  
            }  
        }  
    
        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)  
        {  
            this.BeginInvoke(new Action(() => afterAfterEdit(e.Node)));  
        }  
    
    
        private void afterAfterEdit(TreeNode node)  
        {  
            //Console.WriteLine(node.Parent.Name);  
            //string txt = node.Text;  
            //Console.WriteLine(txt);// Now it is updated  
            string source = File.ReadAllText(@"C:\Users\jusername\Desktop\1.json");  
            JObject data = JObject.Parse(source);  
            var result = data.Properties().ToList();  
            dynamic dydata= JObject.Parse(source);  
           if (node.Parent.Text=="")  
            {  
                //for (int i = 0; i < result.Count(); i++)  
                //{  
                //    if(result[i].Name== node.Tag.ToString())  
                //    {  
                //        result[i].Replace(new JProperty(node.Text, result[i].Value));  
                //    }  
          
                //}  
                 string output = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);  
                File.WriteAllText(@"C:\Users\username\Desktop\1.json", output);  
            }  
            else if(node.Parent.Parent.Tag.ToString()=="")  
            {  
                for (int i = 0; i < result.Count(); i++)  
                {  
                    if (result[i].Name == node.Parent.Tag.ToString())  
                    {  
                        result[i].Replace(new JProperty(result[i].Name, node.Text));  
                    }  
    
                }  
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);  
                File.WriteAllText(@"C:\Users\username\Desktop\1.json", output);  
    
            }  
            else if(node.Parent.Parent.Tag.ToString() == "Question")  
            {  
                //for exmaple Question-Name-height  
                if (node.Parent.Tag.ToString() == "Name")  
                {  
                    var jp = (JProperty)result[4].Value.First().First();  
                    jp.Replace(new JProperty(jp.Name, node.Text));  
    
                }  
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);  
                File.WriteAllText(@"C:\Users\username\Desktop\1.json", output);  
    
            }  
            else if (node.Parent.Parent.Parent.Parent.Tag.ToString() == "")  
            {  
                if (node.Parent.Parent.Tag.ToString() == "SubQuestion"&& node.Parent.Parent.Nodes[0].Nodes[0] == node)  
                {  
                    dydata.Sections[0].Nodes[0].Text=node.Text;  
    
                }  
                else  
                {  
                    dydata.Sections[0].Nodes[1].Text=node.Text;  
                     
                }  
                string output1 = Newtonsoft.Json.JsonConvert.SerializeObject(dydata, Newtonsoft.Json.Formatting.Indented);  
                File.WriteAllText(@"C:\Users\username\Desktop\1.json", output1);  
            }  
    
        }  
    
         
    }  
    

    Result:

    190114-image.png

    Best regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful