在c#中关注树视图中新创建的节点。

问题描述:

实际上我正在尝试使用treeview.select()或treeview.Focus()命令。

但是使用此光标专注于树视图中的默认第一个节点。

但我想关注树视图中新创建的节点。

Actually i was trying it using treeview.select() or treeview.Focus() command.
but using this cursor focusing on by default first node in treeview.
but i want to focus on newly created node in treeview.

您可以使用树视图的选定节点属性,例如,如果您的树视图名为treeView1:


You use the selected node property of the treeview, for example if your treeview is called treeView1:

treeView1.SelectedNode = treeNode;





你也可以调用treeNode.EnsureVisible()来确保树视图中的节点可见。



编辑:



以下是使用评论代码修改的解决方案:





You can also call treeNode.EnsureVisible() to make sure that the node is visible in the treeview.



Here is your revised solution using the code from your comment:

TreeNode newNode = treeViewDept.Nodes.Add(textBoxNewParent.Text);
btnSave.Enabled = true;
treeViewDept.SelectedNode = newNode;
newNode.EnsureVisible();





请注意我在创建新节点时如何保存它?这样我以后可以在设置SelectedNode并使用EnsureVisible时再次引用。



Notice how I save the new node when it is created? This is so it can be referenced again later when I set the SelectedNode and use EnsureVisible.


关注TreeView并隐藏任何选择,同时向用户直观地指示TreeNode刚刚被创建尝试类似这样的东西:
To focus on the TreeView and hide any selection while visually indicating to the user that a TreeNode has just been created try something like this:
private TreeNode tempTreeNode;

private Color nodeBaseColor = Color.White;
private Color justCreatedNodeColor = Color.Yellow;

private void btnMakeNewTreeNode_Click(object sender, EventArgs e)
{
    // reset the background color of the last created node
    if (tempTreeNode != null) tempTreeNode.BackColor = nodeBaseColor;

    // create the new node, add it to the TreeView
    // set its background color
    tempTreeNode = new TreeNode(textBox1.Text);
    treeView1.Nodes.Add(tempTreeNode);
    tempTreeNode.BackColor = justCreatedColor;

    // focus on the TreeView, select the new node
    // then nullify the selection
    treeView1.Focus();
    treeView1.SelectedNode = tempTreeNode;
    treeView1.SelectedNode = null;
}