using treeview, click event on treeview nodes
I am trying to open a Form wh开发者_高级运维en the child node or parent node of a treeview is clicked :
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();
}
}
}
As long as you have only three nodes in your treeview, this might be efficient. However this would require you to write an extra if statement for each new node you add. If you're trying to differentiate on node depth you are better off using the Level
property.
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();
}
}
This may be slightly hackish and abusive of the tag feature but you could do something like this:
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();
}
精彩评论