Question : c# treeview population

First, I know the code is not elegant but it should work...


I am populating a tree from a DT.
The DT has 3 columns/fields per row.
1. Solution Name
2. Table Name
3. Column Name

I have created 3 nodes. SolutionNode, TableNode, ColumnNode.

The attached image illustrates the result.


1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
CODE Snippet

    int i = 0;
            foreach (DataRow row in DT.Rows)
            {
                Solution_Name = DT.Rows[i][0].ToString();
                Table_Name = DT.Rows[i][1].ToString();
                Column_Name = DT.Rows[i][3].ToString();

                TreeNode SolutionNode = new TreeNode(Solution_Name);
                TreeNode ColumnNode = new TreeNode(Column_Name);
                TreeNode TableNode = new TreeNode(Table_Name);

                if (Previous_Solution_Name != Solution_Name)
                {
                    treeView1.Nodes.Add(SolutionNode);
                    SolutionNode.Nodes.Add(TableNode);
                    TableNode.Nodes.Add(ColumnNode);

                    Previous_Solution_Name = Solution_Name;
                    Previous_Table_Name = Table_Name;
                }

***** The below code is executed but the NODE.ADD does not occur. 

                if ((Previous_Table_Name != Table_Name) && (Previous_Solution_Name == Solution_Name))
                {
                    SolutionNode.Nodes.Add(TableNode);
                    TableNode.Nodes.Add(ColumnNode);
                }

                if ((Previous_Table_Name == Table_Name) && (Previous_Solution_Name == Solution_Name))
                {
                    TableNode.Nodes.Add(ColumnNode);

                    Previous_Table_Name = Table_Name;
                }

                i++;
            }
Attachments:
 
Tree View
Tree View
 

Answer : c# treeview population

oops, above code doesn ot work ;) try
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
TreeNode SolutionNode = new TreeNode("?");
TreeNode TableNode = new TreeNode("?");
TreeNode ColumnNode;

foreach (DataRow row in DT.Rows) {
  Solution_Name = row[0].ToString();
  Table_Name = row[1].ToString();
  Column_Name = row[2].ToString();

  ColumnNode = new TreeNode(Column_Name);

  if (SolutionNode.Text != Solution_Name){
    TableNode = new TreeNode(Table_Name);
    SolutionNode = new TreeNode(Solution_Name);

    TableNode.Nodes.Add(ColumnNode);
    SolutionNode.Nodes.Add(TableNode);
    treeView1.Nodes.Add(SolutionNode);
  } else if (TableNode.Text != Table_Name) {
    TableNode = new TreeNode(Table_Name);

    TableNode.Nodes.Add(ColumnNode);
    SolutionNode.Nodes.Add(TableNode);
  } else if ((SolutionNode.Text == Solution_Name) && (TableNode.Text == Table_Name)) {
    TableNode.Nodes.Add(ColumnNode);
  }
}
Random Solutions  
 
programming4us programming4us