Problem with TreeNodeCollection.ContainsKey()
I'm creating a plugin for an application which works with a concept of families. Each Family belongs to a FamilyCategory and each Family contains FamilySymbols. A nice tree structure like that:
- FamilyCategory (Doors)
- Family (External Doors)
- FamilySymbol (Door 2000x1000)
- FamilySymbol (Door 2000x900)
- Family (Garage Doors)
- FamilySymbol (Door 2000x2000)
- FamilySymbol (Door 2100x2000)
- Family (External Doors)
- FamilyCategory (Windows)
- Family (Single Windows)
- FamilySymbol (Window 1000x1400)
- FamilySymbol (Window 800x1400)
- Family (Double Windows)
- FamilySymbol (Window 2000x1400)
- FamilySymbol (Window 2100x1400)
- Family (Single Windows)
Now I'm trying to build a TreeView representing that structure. I have a list of Family objects and each of them has a FamilyCategory开发者_运维知识库 property. I'm trying to determine if a TreeNode with FamilyCategory name already exists and if it does I'm trying to add the Family to that node. If a node for that category doesn't exist I create a new one and add the family there. Unfortunately the code below always evaluates categoryExists as false.
foreach (Family family in families)
{
string familyCategoryName = family.FamilyCategory.Name;
bool categoryExists = treeView.Nodes.ContainsKey(familyCategoryName);
if (categoryExists)
{
categoryNode = treeView.Nodes[familyCategoryName];
}
else
{
categoryNode = new TreeNode(familyCategoryName);
treeView.Nodes.Add(categoryNode);
}
TreeNode familyNode = new TreeNode(family.Name);
categoryNode.Nodes.Add(familyNode);
foreach (FamilySymbol familySymbol in family.Symbols)
{
familyNode.Nodes.Add(familySymbol.Name);
}
}
What am I doing wrong?
try replacing this:
categoryNode = new TreeNode(familyCategoryName);
treeView.Nodes.Add(categoryNode);
by this:
categoryNode = new TreeNode(familyCategoryName);
categoryNode.Name = familyCategoryName;
treeView.Nodes.Add(categoryNode);
(TreeNodeCollection.ContainsKey()
searches the Name
Property, not the Text
Property)
精彩评论