2011-03-29 81 views
-1

我想點擊一個TreeView的子節點或父節點時打開一個表格:使用樹狀,點擊樹狀節點事件

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    TreeNode head = new TreeNode("HEAD"); 

    TreeNode member = new TreeNode("MEMBER "); 

    TreeNode submember = new TreeNode("SUB-MEMBER"); 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     head.Nodes.Add(member); 
     member.Nodes.Add(submember); 

     treeView1.Nodes.Add(head); 
     treeView1.AfterSelect += new TreeViewEventHandler(treeView1_AfterSelect); 

    } 

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) 
    { 
      if (treeView1.SelectedNode == member) 
       { 
        MemberForm mf = new MemberForm(); 
        mf.ShowDialog(); 
       } 

      if (treeView1.SelectedNode == head) 
       { 
        HeadForm hf = new HeadForm(); 
        hf.ShowDialog(); 
       } 

      if (treeView1.SelectedNode == submember) 
       { 
        SubMemberForm sf = new SubMemberForm(); //is this way of checking that which node is clicked efficient??? 
        sf.ShowDialog(); 
       } 
    } 

} 
+1

是的,這是完全有效的。你只是比較對象引用。 – Blorgbeard 2011-03-29 11:29:07

+1

這是什麼問題? – 2011-03-29 11:38:41

+0

嘗試通過編寫這個if(Treeview1.selectednode.text ==「Your Required Node」) – Dotnet 2011-03-29 12:05:35

回答

4

只要你只有三個在樹狀節點,這可能是有效的。但是,這會要求您爲每個添加的新節點編寫額外的if語句。如果您嘗試區分節點深度,則最好使用Level屬性。

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) 
{ 
     if (treeView1.SelectedNode.Level == 0) 
      { 
       HeadForm hf = new HeadForm(); 
       hf.ShowDialog(); 
      } 
     else if (treeView1.SelectedNode.Level == 1) 
      { 
       MemberForm mf = new MemberForm(); 
       mf.ShowDialog(); 
      } 

     else if (treeView1.SelectedNode.Level == 2) 
      { 
       SubMemberForm sf = new SubMemberForm(); 
       sf.ShowDialog(); 
      } 
} 
0

這可能是輕微的hackish和濫用的標籤功能,但你可以做這樣的事情:

TreeNode Head = new TreeNode("Head"); 
Head.Tag = typeof(HeadForm); 

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) 
{ 
    Form toOpen = Activator.CreateInstance((Type)treeView1.SelectedNode.Tag) as Form; 

    if(toOpen != null) 
    toOpen.ShowDialog(); 
}