C# 在树视图中添加子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/881607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding child nodes in treeview
提问by tintincutes
I'm new to C# and don't have any programming experience. But I've finish a C# basics. Now I would like to design a simple tree view by adding parent node and child node.
我是 C# 新手,没有任何编程经验。但是我已经完成了 C# 基础知识。现在我想通过添加父节点和子节点来设计一个简单的树视图。
I would like to add a second child for the Second node, I'm quite stuck here and don't know what's next.
我想为第二个节点添加第二个孩子,我很卡在这里,不知道下一步是什么。
Any ideas?
有任何想法吗?
Here is the code:
这是代码:
private void addParentNode_Click(object sender, EventArgs e)
{
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
}
private void addChildNode_Click(object sender, EventArgs e)
{
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.Nodes[0].Nodes.Add(yourChildNode);
}
Sorry I wasn't clear, I'm not sure if I really need this one here:
对不起,我不清楚,我不确定我是否真的需要这个:
//treeView1.BeginUpdate();
//treeView1.Nodes.Clear();
What I'm trying to do, is to add Parent Nodes and child node. In my code, I can add several Parent Nodes, but if I want to add a child node, it only add in the first parent node. I want that if I add a child node, I want to add it to the second parent or third parent.
我想要做的是添加父节点和子节点。在我的代码中,我可以添加多个父节点,但是如果我想添加一个子节点,它只会添加到第一个父节点中。我希望如果我添加一个子节点,我想将它添加到第二个父节点或第三个父节点。
In my code I only use one treeview here which names as treeview2 Here is the screenshot
在我的代码中,我在这里只使用一个树视图,它命名为 treeview2 这是屏幕截图
this is how my final code looks like: Before I put the else, I'm getting an error if I don't select anything. So I made it that way that if there is nothing selected it will add the "child node" to the "default node" or (parent1 node). It seems to work good. Thanks guys;-)
这就是我的最终代码的样子:在我放置 else 之前,如果我没有选择任何内容,我会收到一个错误。所以我这样做了,如果没有选择任何东西,它会将“子节点”添加到“默认节点”或(parent1节点)。它似乎运作良好。谢谢你们;-)
//This is for adding a parent node
private void addParentNode_Click(object sender, EventArgs e)
{
treeView2.BeginUpdate();
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
treeView2.EndUpdate();
}
//This is for adding child node
private void addChildNode_Click(object sender, EventArgs e)
{
if (treeView2.SelectedNode != null)
{
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.SelectedNode.Nodes.Add(yourChildNode);
treeView2.ExpandAll();
}
//This is for adding the child node to the default node(parent 1 node)
else
{
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.Nodes[0].Nodes.Add(yourChildNode);
}
Additional question: Are there any other ways on how the code be better? Because here, I declare the string "yourChildNode" twice. One in the if and other one in the else, are there any simplification?
附加问题:还有其他方法可以使代码更好吗?因为在这里,我两次声明了字符串“yourChildNode”。一个在if中,另一个在else中,有什么简化吗?
采纳答案by Julien Poulin
It's not that bad, but you forgot to call treeView2.EndUpdate()
in your addParentNode_Click()
method.
You can also call treeView2.ExpandAll()
at the end of your addChildNode_Click()
method to see your child node directly.
还不错,但是你忘记调用treeView2.EndUpdate()
你的addParentNode_Click()
方法了。
您还可以treeView2.ExpandAll()
在addChildNode_Click()
方法末尾调用以直接查看您的子节点。
private void addParentNode_Click(object sender, EventArgs e) {
treeView2.BeginUpdate();
//treeView2.Nodes.Clear();
string yourParentNode;
yourParentNode = textBox1.Text.Trim();
treeView2.Nodes.Add(yourParentNode);
treeView2.EndUpdate();
}
private void addChildNode_Click(object sender, EventArgs e) {
if (treeView2.SelectedNode != null) {
string yourChildNode;
yourChildNode = textBox1.Text.Trim();
treeView2.SelectedNode.Nodes.Add(yourChildNode);
treeView2.ExpandAll();
}
}
I don't know if it was a mistake or not but there was 2 TreeViews. I changed it to only 1 TreeView...
我不知道这是否是一个错误,但有 2 个 TreeView。我把它改成了只有 1 个 TreeView ......
EDIT: Answer to the additional question:
You can declare the variable holding the child node name outside of the if clause:
编辑:回答附加问题:
您可以在 if 子句之外声明包含子节点名称的变量:
private void addChildNode_Click(object sender, EventArgs e) {
var childNode = textBox1.Text.Trim();
if (!string.IsNullOrEmpty(childNode)) {
TreeNode parentNode = treeView2.SelectedNode ?? treeView2.Nodes[0];
if (parentNode != null) {
parentNode.Nodes.Add(childNode);
treeView2.ExpandAll();
}
}
}
Note: see http://www.yoda.arachsys.com/csharp/csharp2/nullable.htmlfor info about the ?? operator.
注意:有关 ?? 的信息,请参见http://www.yoda.arachsys.com/csharp/csharp2/nullable.html 操作员。
回答by Stormenet
Example of adding child nodes:
添加子节点的示例:
private void AddExampleNodes()
{
TreeNode node;
node = treeView1.Nodes.Add("Master node");
node.Nodes.Add("Child node");
node.Nodes.Add("Child node 2");
node = treeView1.Nodes.Add("Master node 2");
node.Nodes.Add("mychild");
node.Nodes.Add("mychild");
}
回答by Byron Ross
It looks like you are only adding children to the first parent treeView2.Nodes[0].Nodes.Add(yourChildNode)
Depending on how you want it to behave, you need to be explicit about the parent node you wish to add the child to.
For Example, from your screenshot, if you wanted to add the child to the second node you would need:treeView2.Nodes[1].Nodes.Add(yourChildNode)
If you want to add the children to the currently selected node, get the TreeView.SelectedNode
and add the children to it.
看起来您只是将子节点添加到第一个父节点treeView2.Nodes[0].Nodes.Add(yourChildNode)
根据您希望它的行为方式,您需要明确说明您希望将子节点添加到的父节点。
例如,从您的屏幕截图中,如果要将子节点添加到第二个节点,则需要:treeView2.Nodes[1].Nodes.Add(yourChildNode)
如果要将子节点添加到当前选定的节点,请获取TreeView.SelectedNode
并将子节点添加到其中。
Try TreeViewto get an idea of how the class operates. Unfortunately the msdn documentation is pretty light on the code samples...
I'm missing a whole lot of safety checks here!
Something like (untested):
尝试TreeView以了解该类的运行方式。不幸的是,msdn 文档中的代码示例非常简单……
我在这里遗漏了很多安全检查!
类似的东西(未经测试):
private void addChildNode_Click(object sender, EventArgs e) {
TreeNode ParentNode = treeView2.SelectedNode; // for ease of debugging!
if (ParentNode != null) {
ParentNode.Nodes.Add("Name Of Node");
treeView2.ExpandAll(); // so you can see what's been added
treeView2.Invalidate(); // requests a redraw
}
}
回答by Roman Polen.
May i add to Stormenet example some KISS (Keep It Simple & Stupid):
我可以在 Stormenet 示例中添加一些 KISS(保持简单和愚蠢):
If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :
如果您已经有一个 treeView 或刚刚创建了它的一个实例:让我们填充一些数据 - 例如。一个父母两个孩子的:
treeView1.Nodes.Add("ParentKey","Parent Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");
Another Ex. two parent's first have two child's second one child:
另一个前 两个父母的第一个有两个孩子的第二个孩子:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");
Take if farther - sub child of child 2:
如果更远 - 孩子 2 的子孩子:
treeView1.Nodes.Add("ParentKey1","Parent-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");
As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!
如您所见,您可以根据需要拥有尽可能多的孩子和父母,而那些孩子可以拥有孩子的子孩子等等......希望我能帮上忙!
回答by Tours
void treeView(string [] LineString)
{
int line = LineString.Length;
string AssmMark = "";
string PartMark = "";
TreeNode aNode;
TreeNode pNode;
for ( int i=0 ; i<line ; i++){
string sLine = LineString[i];
if ( sLine.StartsWith("ASSEMBLY:") ){
sLine = sLine.Replace("ASSEMBLY:","");
string[] aData = sLine.Split(new char[] {','});
AssmMark = aData[0].Trim();
//TreeNode aNode;
//aNode = new TreeNode(AssmMark);
treeView1.Nodes.Add(AssmMark,AssmMark);
}
if( sLine.Trim().StartsWith("PART:") ){
sLine = sLine.Replace("PART:","");
string[] pData = sLine.Split(new char[] {','});
PartMark = pData[0].Trim();
pNode = new TreeNode(PartMark);
treeView1.Nodes[AssmMark].Nodes.Add(pNode);
}
}
回答by Rashedul.Rubel
You may do as follows to Populate treeView with parent and child node. And also with display and value member of parent and child nodes:
您可以执行以下操作来使用父节点和子节点填充 treeView。还有父节点和子节点的显示和值成员:
arrayRoot = taskData.GetRocordForRoot(); // iterate through database table
for (int j = 0; j <arrayRoot.length; j++) {
TreeNode root = new TreeNode(); // Creating new root node
root.Text = "displayString";
root.Tag = "valueString";
treeView1.Nodes.Add(root); //Adding the root node
arrayChild = taskData.GetRocordForChild();// iterate through database table
for (int i = 0; i < arrayChild.length; i++) {
TreeNode child = new TreeNode(); // creating child node
child.Text = "displayString"
child.Tag = "valueString";
root.Nodes.Add(child); // adding child node
}
}
回答by tkflick
I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.
我需要做一些类似的事情,并遇到了同样的问题。我使用 AfterSelect 事件来确保我没有得到之前选择的节点。
It's actually really easy to reference the correct node to receive the new child node.
实际上很容易引用正确的节点来接收新的子节点。
private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
//show dialogbox to let user name the new node
frmDialogInput f = new frmDialogInput();
f.ShowDialog();
//find the node that was selected
TreeNode myNode = TreeView1.SelectedNode;
//create the new node to add
TreeNode newNode = new TreeNode(f.EnteredText);
//add the new child to the selected node
myNode.Nodes.Add(newNode);
}
回答by Bhanu P
Guys use this code for adding nodes and childnodes for TreeView from C# code.*
伙计们使用此代码从 C# 代码中为 TreeView 添加节点和子节点。*
KISS (Keep It Simple & Stupid :)*
吻(保持简单和愚蠢:)*
protected void Button1_Click(object sender, EventArgs e)
protected void Button1_Click(object sender, EventArgs e)
{
{
TreeNode a1 = new TreeNode("Apple");
TreeNode b1 = new TreeNode("Banana");
TreeNode a2 = new TreeNode("gree apple");
TreeView2.Nodes.Add(a1);
TreeView2.Nodes.Add(b1);
a1.ChildNodes.Add(a2);
}
}
回答by koly86
SqlConnection con = new SqlConnection(@"Data Source=NIKOLAY;Initial Catalog=PlanZadanie;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
DataTable dt = new DataTable();
public void loadTree(TreeView tree)
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [RAZDEL_ID],[NAME_RAZDEL] FROM [tbl_RAZDEL]";
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
tree.Nodes.Add(reader.GetString(1));
tree.Nodes[0].Nodes.Add("yourChildNode");
tree.ExpandAll();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Ошибка с сообщением: " + ex.Message);
}
}
回答by Halil Saltik
You can improve that code
您可以改进该代码
private void Form1_Load(object sender, EventArgs e)
{
/*
D:\root\Project1\A\A.pdf
D:\root\Project1\B\t.pdf
D:\root\Project2\c.pdf
*/
List<string> n = new List<string>();
List<string> kn = new List<string>();
n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
foreach (var item in kn)
{
treeView1.Nodes.Add(item.ToString());
}
for (int i = 0; i < treeView1.Nodes.Count; i++)
{
n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
for (int zik = 0; zik < n.Count; zik++)
{
treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
}
}
}