How to Get Node Text of treeView on the click event
Solution 1
I don't recommend using the Click
event for this. The reason is that there are a lot of different places that the user could click on a TreeView control, and many of them do not correspond to an actual node. The AfterSelect
event is a much better choice—it was designed for this usage.
Beyond that, the Click
event is rather difficult to use, because it doesn't provide you very much information in the handler method. It doesn't tell you which button was clicked, where the click event occurred, etc. You have to retrieve all of this information manually. It's recommended that you subscribe to either the MouseClick
or the MouseDown
/MouseUp
event instead.
To figure out what the user clicked on, you need to use the TreeView.HitTest
method, which returns a TreeViewHitTestInfo
object that contains detailed information about the area where the user clicked, or the somewhat simpler TreeView.GetNodeAt
method, which will simply return null
if no node exists at the location of the click.
Alternatively, to get the currently selected node at any time, you can just query the TreeView.SelectedNode
property. If no node is selected, this will also return null
.
Solution 2
It would be better to use treeView1_AfterSelect()
event because that gives the correct selected node text. The treeView1_Click()
event will show the oldest selected not, not the immediate selected one.
You can achieve the selected node text on Click
event
private void treeView1_Click(object sender, EventArgs e)
{
MessageBox.Show(treeView1.SelectedNode.Text);
}
Remember, the difference between Click()
and AfterSelect()
event is their eventargs
treeView1_Click(object sender, EventArgs e)
treeView1_AfterSelect(object sender, TreeViewEventArgs e)
EDIT:
Try out this on Click()
event, I am sure this will help you.
private void treeView1_Click(object sender, EventArgs e)
{
TreeViewHitTestInfo info = treeView1.HitTest(treeView1.PointToClient(Cursor.Position));
if (info != null)
MessageBox.Show(info.Node.Text);
}
Jiss Sebastian
Updated on July 05, 2022Comments
-
Jiss Sebastian almost 2 years
I want to Get the Text of the node in the treeview. I am using the
click()
event.. When I am using theAfterSelect()
event I can get the node text bye.Node.text
. how can I get the text by usingClick()
event