如果我从选定的树视图节点中找到该对象的标签,则在列表中查找和编辑该对象

Finding and editing an object in a list if I have the tag of that object from a selected treeview node

我目前正在为我的应用程序使用 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);
    }

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

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 节点使用情况的功能,可能不需要但是....