My.settings.remove

fantity

Active member
Joined
Mar 10, 2012
Messages
27
Programming Experience
Beginner
I am trying to make a button to remove an item from a listbox as well as my settings. Here is my code:

VB.NET:
 Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        ListBox1.Items.Remove(ListBox1.SelectedItem)
        My.Settings.passwords.Remove(ListBox1.SelectedItem)
        My.Settings.Save()

When I press remove it gets deleted. But when I restart the application it is there again
 
Think about it. The first line in your code gets the SelectedItem of the ListBox and removes it from the ListBox. If that item was just removed then it obviously can't be the SelectedItem any more, so what exactly are you expecting the second line to do?

Basically, you should never have duplicated data such that you need to remove it from two places. You should have one list only. I'm guessing that My.Settings.passwords (why the lower-case "p"?) is a StringCollection. You could just bind that to the ListBox. That way removing it from the underlying list will remove it from the ListBox too. You'd have to make the ListBox refresh its display though, because it won't know that you've removed the item. You'd do that using a BindingSource. You would add a BindingSource to your form and then bind like this:
passwordsBindingSource.DataSource = My.Settings.Passwords
passwordsListBox.DataSource = passwordsBindingSource
and then to remove:
My.Settings.Passwords.Remove(passwordsListBox.SelectedItem)
passwordsBindingSource.ResetCurrentItem()
 
Back
Top