nlkhangit
nlkhangit

Reputation: 71

Windows Form c# - TreeView: unselect item when clicking outside of tree

I have a treeview, with several nodes. If I click OUTSIDE the tree, I want the current selected node to be deselected. But I cannot find the event to trigger, if I click in the white space, the currently selected node remains selected

Upvotes: 3

Views: 2716

Answers (2)

TaW
TaW

Reputation: 54453

For some reason <citation needed> MouseClick will not work when clicking an empty part of a TreeView control. But MouseDown does:

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
    var hit = treeView1.HitTest(e.X, e.Y);

    if (hit.Node == null)
    {
        treeView1.SelectedNode = null;
    }
}

If you also want to deselect when the TreeView looses Focus you can code a suitable event:

private void treeView1_Leave(object sender, EventArgs e)
{
    treeView1.SelectedNode = null;
} 

Update

As per MSDN GotFocus and LostFocus should be avoided for the Enter and Leave events:

The GotFocus and LostFocus events are low-level focus events that are tied to the WM_KILLFOCUS and WM_SETFOCUS Windows messages. Typically, the GotFocus and LostFocus events are only used when updating UICues or when writing custom controls. Instead the Enter and Leave events should be used for all controls except the Form class, which uses the Activated and Deactivate events. For more information about the GotFocus and LostFocus events, see the WM_KILLFOCUS and WM_KILLFOCUS topics.

Note that by default HideSelection is on, so when the TreeView loses Focus the selection is hidden but still valid.

Upvotes: 7

user1845593
user1845593

Reputation: 1844

Before I give my answer, I just would like to tell you that you should demonstrate that you tried and at least give an example to replicate the problem, in your case, the code to add a treeview in the form. None of those things were done! Anyways, here's one possible solution. If this doesn't work for you, it means you have to play around with the events and choose the most appropriate one for your case

public Form1()
{
    InitializeComponent();

    treeView1.Nodes.Add("a");
    treeView1.Nodes.Add("b");
    treeView1.Nodes.Add("c");

    treeView1.LostFocus += (s, e) => ((TreeView)s).SelectedNode = null;
}

Upvotes: 0

Related Questions