How to Get Node Text of treeView on the click event - c#

I want to Get the Text of the node in the treeview. I am using the click() event.. When I am using the AfterSelect() event I can get the node text by e.Node.text . how can I get the text by using Click() event

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.

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

I found a way which works for me, it took me a while to get to do I wanted but it works.
Private Sub toolStripButton7_Click(sender As Object, e As EventArgs) Handles ToolStripButton7.Click
Dim node As TreeNode = treeView1.SelectedNode
Dim strRootPath As String = My.Settings.DefaultRootPath
Dim strNode As String = treeView1.SelectedNode.Text
Call treeViewRoot(strRootPath)
Dim nodes As TreeNode() = treeView1.Nodes.Find(strRootPath & "\" & strNode, True)
For Each node In nodes
treeView1.Focus()
treeView1.SelectedNode = node
Next
End Sub

Related

How to know what Item of a MenuStrip is being clicked?

I'm using c# and I have a MenuStrip control but I don't know how to identify what item of it is being clicked. For example, I used to group all click(buttons) events in one or two methods like "btnActions_click()" or "btnNavigation_click()". Then, inside of the method I identify the button clicked by parsing the sender as a button and placing it on a button var, then I check if the name of that button var is equal to "btnFoo" or "btnBar".
So, in this case, how could I know what item of the MenuStrip controls is being clicked in order to group all click events in only one method?
I apologyze if my english isn't correct. If you can't understand me I can try again or post some code.
Thanks.
Edit: I didn't post any code because I thought that there was not necessary in this question but someone suggest me to do it, so I'll do it. Here's an example of what I do to identify what button has been clicked.
private void btnNavegation_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.Name == "btnNext")
//go to next item of the list
else if (btn.Name == "btnPrevious")
//go to previous item of the list
}
I think that you need to subscribe to ItemClicked event (inherited from ToolStrip), instead of subscribing to Click event (inherited from Control).
The example provided by Microsoft's documentation show you how to determine the clicked item on each call (ToolStripItemClickedEventArgs::ClickedItem):
private void ToolStrip1_ItemClicked(Object sender, ToolStripItemClickedEventArgs e)
{
System.Text.StringBuilder messageBoxCS = new System.Text.StringBuilder();
messageBoxCS.AppendFormat("{0} = {1}", "ClickedItem", e.ClickedItem );
messageBoxCS.AppendLine();
MessageBox.Show(messageBoxCS.ToString(), "ItemClicked Event" );
}

How do I get the UIElement that triggered a MouseDoubleClick Event?

I'm working on a simple IM program as a personal project, and I've hit a bit of a snag. It's really more of a cosmetic thing, but I'm having some trouble with it. I've got a sidebar that lists all of a user's contents in the main window, and I'd like to set it up so that when a user clicks on a contact name, a tab opens in the chat area of the main window with a chat session opened with that contact. The really important part of this is for me to be able to get the UIElement, in this case a Label, that kicked off the MouseDoubleClick event. Once I can access this, I can access the information that I need to make the connection. Unfortunately, I'm a bit rusty with mouse events, and can't figure out how to get back to the Label once the event has been fired. My source code for programmatically creating the label is as follows:
foreach (ContactInfo contact in ContactList)
{
Label currentContact = new Label();
currentContact.Content = contact.ContactName.ToString() + " (" + contact.MachineName.ToString() + ")";
currentContact.MouseDoubleClick += new MouseButtonEventHandler(ContactDoubleClickHandler);
StckPnl_Contacts.Children.Add(currentContact);
}
And the (currently empty) handler is this:
public void ContactDoubleClickHandler(object sender, MouseButtonEventArgs e)
{
}
Am I going about this the wrong way? Any help would be appreciated.
You can inspect the sender (first casting it to the type) to get the element that triggered the event:
Label targetLabel = sender as Label;
if (targetLabel != null)
{
// Do something. I recommend not doing a direct cast in case someone in the future hooks another control type to the event handler.
}
You can use either of following to access the sender details
public void ContactDoubleClickHandler(object sender, MouseButtonEventArgs e)
{
var uiElement = (UIElement) sender; // cast it to UIElement
}
public void ContactDoubleClickHandler(object sender, MouseButtonEventArgs e)
{
var dp = (DependencyObject) sender; // cast it to dependency object.
}
Actually, the sender is your Label, you just have to transform it using:
Label contact = sender as Label;
Be sure to check if contact is null though, before performing any further operations.

How can I keep multiple controls in focus?

I have a tree view on the left side. Selecting a node displays relevant information in a form on the right side.
Would I be able to keep the tree and any one control (textbox, combobox, checkbox) on the right in focus at the same time? This will enable a user to select a field, make a change, select another node, and without having to go back and select the same field again, just type and change the value of the same field.
Thanx.
EDIT
I suppose one could implement such behaviour manually:
private Control __cFocus;
private void {anyControl}_Focus(object sender, EventArgs e)
{
__cFocus = (Control)sender;
}
private void treeView1_AfterSelect(object sender, EventArgs e)
{
__cFocus.Focus();
}
I was just wondering if there exists an automatic / more elegant solution
EDIT 2
Ok, so it seems I'll have to implement it manually. Manual implementation it is then. However, now there seem to be another problem; not sure if I should ask this as a separate question.
When selecting a node the textbox gains focus as intended, but only when using the keyboard. It doesn't work when selecting a node with the mouse. First I thought that it might be a mouse event that's interfering, but stepping revealed that the MouseUp event fired first and then the AfterSelect event which sets the focus, so I don't think it's interfering. The textbox's Enter event is also fired, but for some reason it loses focus again to the tree.
Thanx
no, you cannot keep two controls in focus at the same time. But what you can do is set the focus to the target control in the treeview AfterSelect event
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Focus();
textBox1.SelectAll();
}
then in your textbox leave, save the changes, like so:
private void textBox1_Leave(object sender, EventArgs e)
{
//save changes here
}
this way, everytime you select an item in the treeview, check your textbox for change and save as needed, then you will refocus on the textbox for your next edit
There only can be one element having the focus!
But I have an idea for you that might solve your problem. Assuming you have a window with a TreeView and a TextBox. Set the HideSelection property of the TreeView to false and subscribe the AfterSelect event (like edeperson already answered) like this:
private void OnTreeViewAfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Text = e.Node.Text;
textBox1.Focus();
}
Then subscribe the KeyDown event of the TextBox and do following in the event method:
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Up) || (e.KeyCode == Keys.Down))
{
treeView1.Focus();
SendKeys.Send(e.KeyCode == Keys.Up ? "{UP}" : "{DOWN}");
}
}
At last subscribe the Leave event of the TextBox and do following in the event method:
private void OnTextBoxLeave(object sender, EventArgs e)
{
if (treeView1.SelectedNode != null)
{
treeView1.SelectedNode.Text = textBox1.Text;
}
}
And, voilá it should work like you expected it...
If you want to focus on it , you can use usercontrol. you can put your textbox on usercontrol and set focus of this textbox on usercontrol using set properties on treeview select.
No you may not, only one control may be in focus at any given time.
See Moonlight's comment for one way to achieve the behavior that you seek.

Calling code-behind method on TreeNode click

I want to call a code-behind method when a TreeNode is clicked in my TreeView. I would imagine this isn't difficult to do, but I can't find a good example of how to do it.
I've looked at TreeNodeSelectAction, but that appears to just be an enumeration, so I'm wondering how I can call my own code when a node is clicked.
Try add the SelectedNodeChanged event handler to the TreeView control. Then, you can select the method by the TreeNode name.
protected void MyTreeView_SelectedNodeChanged(object sender, EventArgs e)
{
TreeView treeView = sender as TreeView;
if (treeView != null)
{
TreeNode treeNode = treeView.SelectedNode;
}
}
Hope it helps

TreeNode Selection Problems in C#

Whenever I click outside the tree nodes text, on the control part, it tigers a node click event- but doesn't highlight the node. I am unsure why this is happening.
I want the node to be selected on a click- when you click the nodes text- not the whitespace- I only assume that the nodes width reaches across the whole Treenode? I have the Treeview on dock.fill mode if that has something to do with it- I tried everything but can't get it to behave correctly.
Maybe someone will know what's going on.
Update:
if (e.Location.IsEmpty)
{
Seems to work better- but still selects the node in the blank place where there is no text- Obviously the node width extends across the whole treeview it seems?
Is there a better way to accomplish what I want? Or is that the best way?
UPDATE: Previous idea isn't working- sigh- I thought it did it but it didn't.
New Problem : I think part of the problem is related to the focus now when I switch from treeview.
UPDATE-
The only code I came up with about disabling right mouse click to select node on beforeSelect event is
if (MouseButtons == System.Windows.Forms.MouseButtons.Right)
{
e.Cancel = true;
}
But it didn't work- any help is appreciated- following suggestions of only answer, for more details.
You should use the treeView.HitTest method to determine which part of the node has been clicked.
private bool IsClickOnText(TreeView treeView, TreeNode node, Point location)
{
var hitTest = treeView1.HitTest(location);
return hitTest.Node == node
&& hitTest.Location == TreeViewHitTestLocations.Label;
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if(IsClickOnText(treeView1, e.Node, e.Location))
{
MessageBox.Show("click");
}
}
private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
var position = treeView1.PointToClient(Cursor.Position);
e.Cancel = !IsClickOnText(treeView1, e.Node, position);
}
}
Use the .AfterSelect and/or .BeforeSelect events to handle the selection processing instead of the .Click event. Then it will select the node only when you click on the text, and it won't fire .AfterSelect or .BeforeSelect when you click on the white space.

Categories

Resources