Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deselect in treeView

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.

like image 844
Beef Avatar asked Jul 09 '26 16:07

Beef


2 Answers

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

like image 59
Johnston Avatar answered Jul 11 '26 06:07

Johnston


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.

like image 20
Brennan Vincent Avatar answered Jul 11 '26 07:07

Brennan Vincent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!