mjsr
mjsr

Reputation: 7590

get text of the clicked node treeview C# winforms

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

Upvotes: 0

Views: 22922

Answers (4)

Eric Chai
Eric Chai

Reputation: 650

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);
}

Upvotes: 0

Cody Gray
Cody Gray

Reputation: 244752

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);
}

Upvotes: 3

Developer
Developer

Reputation: 8636

 private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
 {
    treeView1.SelectedNode = e.Node;
 }

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941505

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.

Upvotes: 8

Related Questions