我正在尝试在单击树视图的子节点或父节点时打开一个Form:
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();
}
}
}
答案 0 :(得分: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();
}
}
答案 1 :(得分:0)
这可能会略微破解并滥用标记功能,但您可以执行以下操作:
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();
}