TreeNode已存在但treenode.nodes.ContainsKey("Nodename")返回false问题咨询
TreeNode.Nodes.ContainsKey() Returns False When the Node Exists Hey there! Let's break down why you're seeing this behavior and how to fix it.
The Core Issue
The TreeNodeCollection.ContainsKey() method looks for a node using its Name property, not the Text property. Looking at your code, when you create new TreeNode instances, you're only setting the Text property (e.g., n.Text = file;) but never setting the Name property. That means even though the node shows up in the tree with the correct text, the collection doesn't recognize it when you search by that text via ContainsKey().
Fix 1: Set the Name Property When Creating Nodes
The simplest fix is to explicitly set the Name property to match the Text (or whatever value you want to use as the key) when you create each node:
if (file.Contains(".exe")) { TreeNode n = new TreeNode(); n.ImageIndex = 1; n.Text = file; n.Name = file; // Add this line to set the key x.Nodes.Add(n); } else if (file.Contains(".txt") || file.Contains(".doc") || file.Contains(".rtf")) { TreeNode n = new TreeNode(); n.ImageIndex = [your target index]; // Fill in your desired image index n.Text = file; n.Name = file; // Don't forget this key property! x.Nodes.Add(n); }
Now, when you call x.Nodes.ContainsKey("YourNodeText"), it will correctly find the node because the Name property matches the key you're searching for.
Fix 2: Search by Text Instead (If You Prefer)
If you don't want to set the Name property, you can use LINQ to check for a node by its Text value instead. Just make sure you have the System.Linq namespace imported:
using System.Linq; // Later in your code... bool nodeExists = x.Nodes.Cast<TreeNode>().Any(node => node.Text == "Nodename");
Bonus: Watch for Hidden Whitespace
Another possible gotcha: if the file string from your server response has leading/trailing spaces, the Text (and Name, if you set it) will include those spaces. When you search for "Nodename" without those spaces, the check will fail. To fix this, trim the file string before using it:
string trimmedFile = file.Trim(); n.Text = trimmedFile; n.Name = trimmedFile;
内容的提问来源于stack exchange,提问作者Adrian Rudy Dacka

