patterncsharpMinor
Add ImageIndex to Treeview
Viewed 0 times
imageindextreeviewadd
Problem
As the title states. I need a different type of icon for the different nodes types. at the moment I have this hacky way of achieving that.
I do not want to add the long list of else if's.
for (var x = 0; x <= nodeList.Count - 1; x++)
{
if (xNode.Attributes["TYPE"].Value == "server.point.AV")
{
var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, AnalogImagesIndex, AnalogImagesIndex);
inTreeNode.Nodes.Add(tNode2);
tNode2 = inTreeNode.Nodes[x];
AddNode(xNode, tNode2);
}
else if (xNode.Attributes["TYPE"].Value == "schedule.NSPDigitalSchedule")
{
var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, ScheduleImageIndex, ScheduleImageIndex);
inTreeNode.Nodes.Add(tNode2);
tNode2 = inTreeNode.Nodes[x];
AddNode(xNode, tNode2);
}
else if (xNode.Attributes["TYPE"].Value == "server.point.SV")
{
var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, StringImageIndex, StringImageIndex);
inTreeNode.Nodes.Add(tNode2);
tNode2 = inTreeNode.Nodes[x];
AddNode(xNode, tNode2);
}
else if (xNode.Attributes["TYPE"].Value.StartsWith("trend"))
{
var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, TrendImageIndex, TrendImageIndex);
inTreeNode.Nodes.Add(tNode2);
tNode2 = inTreeNode.Nodes[x];
AddNode(xNode, tNode2);
}
.
.
.and so onI do not want to add the long list of else if's.
Solution
The moment you start copy-pasting code and only changing one small thing, it's time to move that code to a method.
I'm assuming
Moreover, all of those
private void CreateAndAddNode(WhateverTypeImagesIndexIs imagesIndex, int x)
{
var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, imagesIndex, imagesIndex);
inTreeNode.Nodes.Add(tNode2);
tNode2 = inTreeNode.Nodes[x];
AddNode(xNode, tNode2);
}I'm assuming
AnalogImagesIndex etc. all inherit from some base type; that's the one to use as the method's parameter.Moreover, all of those
ifs can be changed to a switch.Code Snippets
private void CreateAndAddNode(WhateverTypeImagesIndexIs imagesIndex, int x)
{
var tNode2 = new TreeNode(xNode.Attributes["NAME"].Value, imagesIndex, imagesIndex);
inTreeNode.Nodes.Add(tNode2);
tNode2 = inTreeNode.Nodes[x];
AddNode(xNode, tNode2);
}Context
StackExchange Code Review Q#140537, answer score: 3
Revisions (0)
No revisions yet.