我有两个树视图和一个带有添加节点功能的contexmenucontainer cmnuAddNode是我的contexmenuestrip的添加选项卡 我是一个与事件合作的新手
如果点击,我想将节点添加到树视图1 如果单击,则将节点添加到treeview2 我只是想知道在if条件下我应该写什么 我的代码如下:
private void cmnuAddNode_Click(object sender, EventArgs e)
{
NewNode n = new NewNode();
n.ShowDialog();
TreeNode nod = new TreeNode();
nod.Name = n.NewNodeName.ToString();
nod.Text = n.NewNodeText.ToString();
n.Close();
if (treeView1.SelectedNode!=null)
{
treeView1.SelectedNode.Nodes.Add(nod);
treeView1.SelectedNode.ExpandAll();
}
if (treeView2.SelectedNode!= null)
{
treeView2.SelectedNode.Nodes.Add(nod);
treeView2.SelectedNode.ExpandAll();
}
}
单击treeview2时,此代码有异常
答案 0 :(得分:1)
private void cmnuAddNode_Click(object sender, EventArgs e,TreeViewEventArgs e1)
{
NewNode n = new NewNode();
n.ShowDialog();
TreeNode nod = new TreeNode();
nod.Name = n.NewNodeName.ToString();
nod.Text = n.NewNodeText.ToString();
n.Close();
if(e1.Node.TreeView == treeView1)
{
treeView1.SelectedNode.Nodes.Add(nod);
treeView1.SelectedNode.ExpandAll();
}
if(e1.Node.TreeView == treeView2)
{
treeView2.SelectedNode.Nodes.Add(nod);
treeView2.SelectedNode.ExpandAll();
}
}
答案 1 :(得分:0)
首先为每个TreeView添加一个鼠标单击事件 其次,使用MouseEventArgs选择正确的节点。 for treeview1(对treeview2做同样的事情)
void treeView1MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
// Select the clicked node
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
if(treeView1.SelectedNode != null)
{
cmnuAddNode.Show(treeView1, e.Location);
}
}
}
//it will work for the two treeview getting Parent control of cmnuAddNode
private void cmnuAddNode_Click(object sender, EventArgs e,TreeViewEventArgs e1)
{
TreeView yourtreeView = (TreeView)cmnuAddNode.Parent;
NewNode n = new NewNode();
n.ShowDialog();
TreeNode nod = new TreeNode();
nod.Name = n.NewNodeName.ToString();
nod.Text = n.NewNodeText.ToString();
n.Close();
yourtreeView.SelectedNode.Nodes.Add(nod);
yourtreeView.SelectedNode.ExpandAll();
}
答案 2 :(得分:0)
简单我在我的树视图中获得了一个索引,当它在事件鼠标点击它的树视图1时我将它设置为1而当它转到2时我将其设置为2 所以在我的函数中添加我写的条件这简单,快速,简单
private void cmnuAddNode_Click(object sender, EventArgs e)
{
NewNode n = new NewNode();
n.ShowDialog();
TreeNode nod = new TreeNode();
nod.Name = n.NewNodeName.ToString();
nod.Text = n.NewNodeText.ToString();
n.Close();
if (treeviewindex== 1)
{
treeView1.SelectedNode.Nodes.Add(nod);
treeView1.SelectedNode.ExpandAll();
}
if (treeviewindex==2)
{
treeView2.SelectedNode.Nodes.Add(nod);
treeView2.SelectedNode.ExpandAll();
}
if (treeviewindex == 3)
{
treeView3.SelectedNode.Nodes.Add(nod);
treeView3.SelectedNode.ExpandAll();
}
}