So I have a wpf c# application thats information from a file, loads them to a list, then loads the list onto the treeView, it also has buttons to edit, delete, add the information, how i do this is edit the information in the list, then overwrite the text file with the edited list information, and then there is a update button used to update the treeView, and when I update the treeView i deleted everything from the list, then reload the list with the updated text file then clear the treeView and then reload the list data into the treeView. Now the reason it crashes in my updated is on this line treeView1.Items.Clear(); and then it takes me to this line string selectName = ((TreeViewItem)(treeView1.SelectedItem)).Header.ToString(); which is in my treeView1_SelectedItemChanged code, so I understand why its crashing, is there a way to have it deselect anything in the treeView right before I clear it, so it doesnt try to clear a selected item. Thanks. name and details are both list.
Try adding a flag that trips off when you clear the treeview. Then put your action event body code inside an if checking the flag
treeView1.SelectedItem
will be null, since you have just cleared the treeview.
You should ask yourself what sense it makes to try to get the header of an item in a tree view whose items have just been cleared, and address why that line is being called at that point in your program.
I can't help you further without more context.
EDIT: Sorry, I misunderstood what you were asking. Yes, you can clear selection, but that too will cause the selection changed event to fire. What you should do is check in the event handler that SelectedItem is not null before continuing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With