查找和编辑列表中的对象,如果我有来自选定树视图节点的对象的标签

本文关键字:对象 标签 节点 视图 列表 编辑 查找 如果 | 更新日期: 2023-09-27 18:34:37

我目前为我的应用程序提供了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 变量。在组窗体中,您可以直接对其进行编辑,当您返回时,实例已经更新。

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