如果我从选定的树视图节点获得该对象的标记,则查找并编辑列表中的对象

时间:2016-02-14 21:27:14

标签: c# winforms list treeview

我目前为我的应用程序提供了newdelete个函数,但我正在尝试弄清楚如何在我的树视图中的所选节点上实现edit。目前我可以更改节点的文本,但这并不是要更改存储在列表对象中的实际名称。怎么会这样做?这是我到目前为止的代码:

    private void OnGroupEditClick(object sender, EventArgs e)
    {
        GroupForm groupForm = new GroupForm();
        if (groupForm.ShowDialog() != DialogResult.OK)
            return;

        _treeViewGroups.SelectedNode.Text = groupForm.Group.Name;
    }

如果有帮助,请按以下方式实施newdelete

    private void OnGroupNewClick(object sender, EventArgs e)
    {
        GroupForm groupForm = new GroupForm();
        if (groupForm.ShowDialog() != DialogResult.OK)
            return;

        Group group = groupForm.Group;
        KeyPassManager.addGroup(group);

        TreeNode node = _treeViewGroups.Nodes.Add(group.Name);
        _treeViewGroups.SelectedNode = node;
        node.Tag = group;
    }

    private void OnGroupDeleteClick(object sender, EventArgs e)
    {
        DeleteConfirmation deleteConfirmation = new DeleteConfirmation();

        if (deleteConfirmation.ShowDialog() != DialogResult.OK)
            return;

        Group group = (Group)_treeViewGroups.SelectedNode.Tag;

        KeyPassManager.removeGroup(group);
        _treeViewGroups.Nodes.Remove(_treeViewGroups.SelectedNode);
    }

1 个答案:

答案 0 :(得分:1)

创建GroupForm进行编辑时,应通过表单构造函数传递从SelectedNode的Tag属性中提取的Group变量。在组表单中,您可以直接编辑它,当您返回时,实例已经更新。

private void OnGroupEditClick(object sender, EventArgs e)
{
    if(_treeViewGroups.SelectedNode != null)
    {
        // Extract the instance of the Group to edit
        Group grp = _treeViewGroups.SelectedNode.Tag as Group;

        // Pass the instance at the GroupForm 
        GroupForm groupForm = new GroupForm(grp);
        if (groupForm.ShowDialog() != DialogResult.OK)
            return;
        _treeViewGroups.SelectedNode.Text = groupForm.Group.Name;
    }
}

在GroupForm对话框中,您将收到传递的实例,并以这种方式将其保存在全局变量中

public class GroupForm: Form
{
   private Group _groupInEdit = null;

   public Group Group
   {
       get { return _groupInEdit; }
   }

   public GroupForm(Group grp = null)
   {
       InitializeComponent();
       _groupInEdit = grp;
   }
   private void GroupForm_Load(object sender, EventArgs e)
   {
       if(_grpInEdit != null)
       {
           ... initialize controls with using values from the 
           ... instance passed through the constructor
       }
   }
   private void cmdOK_Click(object sender, EventArgs e)
   {
       // If the global is null then we have been called from 
       // the OnGroupNewClick code so we need to create the Group here
       if(_grpInEdit == null)
          _grpInEdit = new Group();

       _grpInEdit.Name = ... name from your textbox...
       ... other values
   }
}

添加了一些关于TreeView节点使用情况的检查,可能不需要,但......