user3481276
user3481276

Reputation: 89

System.NullReferenceException while getting the parent from a TreeView?

I want to write some code, where I can delete a single item from TreeView by clicking a "DELETE" button. I suppose I have implemented the codes correctly, but in the end I still get a NullReferenceException: "Object reference not set to an instance of an object."

private void Functions_KeyDown(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.Delete:
            DeleteData_Functions();
            break;
        default:
            break;
    }
}

public void DeleteData_Functions()
{
    TreeViewItem parent = (tv_Function.SelectedItem as TreeViewItem).Parent as TreeViewItem;
    parent.Items.Remove(tv_Function.SelectedItem);
}

tv_Function is the name of my TreeView. I supposed that when I selected the item I want to delete and click delete, it should have return some values instead of null.

Upvotes: 0

Views: 687

Answers (1)

George Vovos
George Vovos

Reputation: 7618

 TreeViewItem t1=tv_Function.SelectedItem as TreeViewItem;
 if(t1==null)
       return;//or throw exception or whatever you want

 TreeViewItem parent =t1.Parent as TreeViewItem;
 if(parent==null)
       return;//or throw exception or whatever you want

 parent.Items.Remove(tv_Function.SelectedItem);

Your problem is that one of the variables is not a TreeViewItem (or it is and it is null)

If you need the selected Item as TreeViewItem use this code

 TreeViewItem t1 = tv_Function.ItemContainerGenerator.ContainerFromItem(tv_Function.SelectedItem) as TreeViewItem; 

If you have set the ItemSource property of the your tree your "remove" line will not work.

Remove the object from the itemsource like this

Software t1 = myTree.SelectedItem as Software;
TheTreesItemSourceCollection.Remove(t1);

Upvotes: 2

Related Questions