i have a difficulty selecting the text of a node in a treeview in c#, the idea is get the text of the clicked node, but the problem is that when i want to grab it like this
MessageBox.Show(treeView1.SelectedNode.Text);
the selected node is the previous selected, not the actual that i'm clicking, so how can 开发者_开发技巧i select first the node that i'm clicking and then grab his text after that? the solution i think is call the original nodeclick handler before i grab the text but i don't know how to call it
Yes, it isn't selected yet when the NodeMouseClick event fires. You ought to use the AfterSelect event instead. That ensures it also works when the user uses the keyboard to select the node. Or do it like this:
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
Console.WriteLine(e.Node.Text);
}
But beware that the selection can be canceled by BeforeSelect.
You're correct in assuming that you're probably trying to access the SelectedNode
property of the TreeView
control before the node that was clicked actually gets set as selected. However, the answer here is not to call the event yourself (that causes all kinds of problems, and is generally a bad practice).
In fact, there's a much simpler solution. The NodeMouseClick
event passes in an instance of the TreeNodeMouseClickEventArgs
, which exposes a Node
property indicating the node that was just clicked.
So you can change your code to simply access that property:
void treeView1_NodeMouseClick(Object sender, TreeNodeMouseClickEventArgs e)
{
MessageBox.Show(e.Node.Text);
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
treeView1.SelectedNode = e.Node;
}
I use AfterSelect
event and a Button with a Clicked
event to show the selected node text, and it works fine:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
Console.WriteLine(e.Node.Text);
}
private void button1_Click(object sender, EventArgs e) {
Console.WriteLine(treeView1.SelectedNode.Text);
}
精彩评论