C #: Help determine the selected node index in TreeView. NullReferenceException Error?

I'm trying to make sure that I can fire certain events when a node is selected in the TreeView. I run the code and I get an error message that reads NullReferenceException was unhandled: the object reference was not set to the object instance.

Any tips on how to overcome this obstacle?

    private void tvNodes_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        switch (tvNodes.SelectedNode.Index)
        {
            case 0:
                //first item
                break;

            case 1:
                //second item
                break;

            case 2:
                //third item
                break;
        }
    } 
+3
source share
3 answers

tvNodes.SelectedNodedoes not match the node you clicked on and may be null. Use instead e.Node.Index. And I'm paranoid; I will probably still verify that e.Nodeit is not the nullfirst ...

    if(e.Node == null) return;
    switch (e.Node.Index)
    {
        case 0:
            //first item
            break;

        case 1:
            //second item
            break;

        case 2:
            //third item
            break;
    }
+4
source
private void tvNodes_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
    var index = null != e.Node ? e.Node.Index : -1;
    switch (index) {
        case 0:
            //first item
            break;
        case 1:
            //second item
            break;
        case 2:
            //third item
            break;
    }
}
0
source

, , node TreeView.

, AfterSelect NodeMouseClick:

private void tvNodes_AfterSelect(object sender, TreeViewEventArgs e)
{
     switch (e.Node.Index)
    {
        case 0:
            //first item
            break;

        case 1:
            //second item
            break;

        case 2:
            //third item
            break;
    }

}

, AfterSelect node, . NodeMouseClick , node . MSDN:

, node , , (+) (-), , node .

SelectedNode , [+] [-].

0

Source: https://habr.com/ru/post/1705771/


All Articles