简体   繁体   中英

C# How to replace selected node text without removing the child node on treeview?

在此处输入图片说明

I have a treeview node with 3 layer of hierarchy. Currently, the function for Add, Remove working. They only left is append the modified text into the selected node without remove the node before insert?

I have seen some of the question on this forum and from search engine result but the solutions look not like what I need.

Solutions that I found:-

  1. Get the selected node index, remove it, insert new to selected index node. On here

  2. Loop inside treeview node, to find and replace selected node string with new string. On here .

Why I can't follow above idea?

  1. If the selected node were remove first, so does the child will remove too?
  2. If there is more than 1 node that have same text, it must be replace on recursive loop.

What I have now are the index of Parent and Current Selected. So, it will be two index of hierarchy.

indxparent.Text = TreeView1.SelectedNode.Parent.Index.ToString() ?? "-";
indxchild.Text = TreeView1.SelectedNode.Index.ToString() ?? "-";

How to programming of amend new text to the selected node/ to the selected node index?

Working code use before Kempeth proposed his solutions:
Method 1:

string newdata = "This is new information data";
TreeView1.LabelEdit = true;
if (!TreeView1.SelectedNode.IsEditing)
{
    TreeView1.SelectedNode.BeginEdit();
    TreeView1.SelectedNode.Text = newdata;
    TreeView1.SelectedNode.EndEdit(false);
}  

Method 2:

string newdata = "This is new information data";
TreeNode node = new TreeNode(newdata);
TreeView1.SelectedNode.Parent.Nodes.RemoveAt(IndexOfSelectedNode);
TreeView1.SelectedNode.Parent.Nodes.Insert(IndexOfSelectedNode, node);
TreeView1.SelectedNode = node;

您是否尝试过简单地设置SelectedNodeText属性?

TreeView1.SelectedNode.Text = TreeView1.SelectedNode.Text + " MAGIC!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM