C# 运行时编辑 节点重命名

方法一: 
int nodeIndex = 0;
        bool nodeChanged = false;
 
        //右键点击,就进入修改状态
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                e.Node.BeginEdit();
            }
        }
 
        private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            nodeIndex = e.Node.Index;
            nodeChanged = true;
 
            e.Node.EndEdit(true );
        }
 
        private void treeView1_NodeMouseHover(object sender, TreeNodeMouseHoverEventArgs e)
        {
            if (nodeChanged == true)
            {
                //在这里保存数据到数据库
                MessageBox.Show(treeView1.Nodes[nodeIndex].Text);
 
                nodeChanged = false;
            }
        }
方法二:
方法二:
MouseClick和AfterLabelEdit的使用,treeView1.LabelEdit = true;这句不可缺少:
public Form1()
{
    InitializeComponent();
    this.Load+=new EventHandler(Form1_Load);
    treeView1.MouseClick+=new MouseEventHandler(treeView1_MouseClick);
    treeView1.AfterLabelEdit+=new NodeLabelEditEventHandler(treeView1_AfterLabelEdit);
}
 
private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 10; i++)
    {
        treeView1.Nodes.Add("tv" + i.ToString());
        treeView1.Nodes[i].Nodes.Add("tvc"+i.ToString());
    }
    treeView1.LabelEdit = true;//不可缺少
}
 
private void treeView1_MouseClick(object sender, MouseEventArgs e)
{
    TreeView tv=(TreeView)sender;//获取treeview
    if (e.Button == MouseButtons.Right)//判断是否鼠标右键
    {
        if (tv.SelectedNode != null)//判断是否存在选择节点
            tv.SelectedNode.BeginEdit();
    }
}
private void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
    string newTxt = e.Label;//获取新文本
    //string id = e.Node.Text;//获取原来的文本
 
    //进行你的更新操作
 
}

原文地址:http://www.cnblogs.com/better-than-ever/p/3222883.html  感谢原博主。在这里只是记录。

 

 

posted @ 2016-02-24 11:28  持之  阅读(615)  评论(0编辑  收藏  举报