Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Building the Employee Tree

We start by creating a CEO Employee and then add his or her subordinates and their subordinates, as follows.

 private void buildEmployeeList() {
    prez = new Boss("CEO", 200000);
    marketVP = new Boss("Marketing VP", 100000);
    prez.add(marketVP);
    salesMgr = new Boss("Sales Mgr", 50000);
    advMgr = new Boss("Advt Mgr", 50000);
    marketVP.add(salesMgr);
    marketVP.add(advMgr);
    prodVP = new Boss("Production VP", 100000);
    prez.add(prodVP);
    advMgr.add("Secy", 20000);
    //add salesmen reporting to sales manager
    for (int i = 1; i<=5; i++){
       salesMgr.add("Sales" + i.ToString(),
           rand_sal(30000));
    }

    prodMgr = new Boss("Prod Mgr", 40000);
    shipMgr = new Boss("Ship Mgr", 35000);
    prodVP.add(prodMgr);
    prodVP.add(shipMgr);

    for (int i = 1; i<=3; i++){
       shipMgr.add("Ship" + i.ToString(), rand_sal(25000));
    }
    for (int i = 1; i<=4; i++){
       prodMgr.add("Manuf" + i.ToString(), rand_sal(20000));
    }
 } 

Once we have constructed this Composite structure, we can load a visual TreeView list by starting at the top node and calling the addNode() method recursively until all the leaves in each node are accessed.

 private void buildTree() {
    EmpNode nod;
    nod = new EmpNode(prez);
    rootNode = nod;
    EmpTree.Nodes.Add(nod);
    addNodes(nod, prez);
 } 

To simplify the manipulation of the TreeNode objects, we derive an EmpNode class that takes an instance of Employee as an argument.

 public class EmpNode:TreeNode  {
    private AbstractEmployee emp;
    public EmpNode(AbstractEmployee aemp ):
           base(aemp.getName ()) {
       emp = aemp;
    }
    //-----
    public AbstractEmployee getEmployee() {
       return emp;
    }
 } 

The final program display is shown in Figure 16-3.

Figure 16-3Figure 16-3. The corporate organization shown in a TreeView control


In this implementation, the cost (sum of salaries) is shown in the bottom bar for any employee you click on. This simple computation calls the getChild() method recursively to obtain all the subordinates of that employee.

 private void EmpTree_AfterSelect(object sender,
       TreeViewEventArgs e) {
    EmpNode node;
    node = (EmpNode)EmpTree.SelectedNode;
    getNodeSum(node);
 }
 //------
 private void getNodeSum(EmpNode node) {
    AbstractEmployee emp;
    float sum;

    emp = node.getEmployee();
    sum = emp.getSalaries();
    lbSalary.Text = sum.ToString ();
 } 
  • + Share This
  • 🔖 Save To Your Account