Search code examples
vb.netcomboboxmy.settings

How to overwrite Combobox item with textbox instead of duplicating it


I am trying to have a button generate a text file and save a new combobox item based on what is entered in the combobox field or replace an existing one but it seems to be adding a new entry every time. It overwrites the text file it generates just fine.

I tried having the button delete the combobox entry that matches the name entered and then add a new one with the same name but when i do that it clears the combobox field and enters a blank item. This is the original code without the remove part.

Sub Button9Click(sender As Object, e As EventArgs)
        My.Computer.FileSystem.WriteAllText("C:\Users\" & Environment.UserName & "\desktop\Templates\" & comboBox2.text & ".txt",TextBox4.Text, False)
        ComboBox2.Items.Add(comboBox2.Text)
End Sub

For example if I Put "Test" in the combobox field and click save twice, i get two "test" items. then If I use a delete button that has:

Sub Button10Click(sender As Object, e As EventArgs)
        My.Computer.FileSystem.DeleteFile ("C:\Users\" & Environment.UserName & "\desktop\templates\" & comboBox2.text & ".txt")
        comboBox2.Items.remove(comboBox2.Text)
End Sub

it deletes only one entry. if I do it again to remove the duplicate, since the text file no longer exists, the program crashes.

How can I write this so if what is written in the combobox matches an existing entry exactly, it overwrites the existing item? It does overwrite the text document it creates, no problem as is.


Solution

  • Under the click event of the button, simply check if the item already exists before adding it to the combo box. Try this:

    Sub Button9Click(sender As Object, e As EventArgs)
        My.Computer.FileSystem.WriteAllText("C:\Users\" & Environment.UserName & "\desktop\Templates\" & comboBox2.text & ".txt",TextBox4.Text, False)
        If (Not ComboBox2.Items.Contains(comboBox2.Text)) Then
            ComboBox2.Items.Add(comboBox2.Text)
        End If
    End Sub