TreeView AfterExpand event sometimes doesn't work C #
I have a TreeView and subscribed to the "TreeViewConnections_AfterExpand" and "" event. each TreeNode contains MenuScript events. and the following code:
//event
private void TreeViewConnections_AfterExpand(object sender, TreeViewEventArgs e)
{
var activeKey = e.Node.ImageKey.Replace("Inactive", "Active");
e.Node.ImageKey = activeKey;
e.Node.SelectedImageKey = activeKey;
}
//event
private void TreeViewConnections_MouseClick(object sender, MouseEventArgs e)
{
var currentNode = this.treeViewConnections.GetNodeAt(e.Location);
if (currentNode == null) return;
var currentBounds = currentNode.Bounds;
Rectangle bounds = new Rectangle(currentBounds.Left - ExpandIcon.Width, currentBounds.Y, currentBounds.Width - 5, currentBounds.Height);
if (bounds.Contains(e.Location)) return;
this.treeViewConnections.SelectedNode = currentNode;
if (e.Button == MouseButtons.Right)
{
SetupConnectionMenus(currentNode);
}
}
private void SetupConnectionMenus(TreeNode node)
{
var isOpened = node.Nodes.Count > 0;
if (node.ContextMenu == null)
{
var menu = new ContextMenuStrip();
menu.Items.AddEx("Open Connection", node.Name + "_Open", !isOpened, onClick: OpenConnection_Click, context: node);
menu.Items.AddEx("Close Connection", node.Name + "_Close", isOpened, onClick: CloseConnection_Click, context: node);
node.ContextMenuStrip = menu;
}
}
//event
private void OpenConnection_Click(object sender, EventArgs e)
{
var menuItem = sender as ToolStripMenuItem;
var currentNode = menuItem.Tag as TreeNode;
OpenConnection(currentNode);
}
//event
private void CloseConnection_Click(object sender, EventArgs e)
{
var menuItem = sender as ToolStripMenuItem;
var currentNode = menuItem.Tag as TreeNode;
currentNode.Nodes.Clear();
currentNode.Collapse();
}
private void OpenConnection(TreeNode node)
{
treeViewConnections.BeginUpdate();
//add child node to the node.
treeViewConnections.EndUpdate();
node.Expand(); //?????
}
TreeViewConnections_AfterExpand doesn't work sometime. as it shown on the picture:
But in this case, is there something else I need to do?
+3
source to share
1 answer
This issue is the cause of Node.Collapse error and Node.Nodes.Clear () caused problems. correct as below:
private void CloseConnection_Click(object sender, EventArgs e)
{
var menuItem = sender as ToolStripMenuItem;
var currentNode = menuItem.Tag as TreeNode;
currentNode.Collapse(); // Here will verify whether the current node has child nodes.
currentNode.Nodes.Clear();
}
+1
source to share