in form1 i have two listboxs listbox1 listbox2 loadbutton and savebutton

this code will write listbox1.selecteditem into a txt file and loadbutton will load info

in listbox2 but i want when i click loadbutton it check if that item is already exist in

listbox2 , if not so write selected item from listbox1 and if that item is already exist in listbox2 then do not save it (msg"this item is already exist in listbox2")

but this is not work well

Dim wri As New IO.StreamWriter("e:\test.txt", True)

    If ListBox2.ToString.Contains(ListBox1.Items.Item) Then ' or ListBox1.SelectedItem ? ' not work i tried more  ListBox2.ToString.CompareTo(ListBox1.SelectedItem) not work ):

        MsgBox("this item is already in listbox2")
    Else

        wri.WriteLine(ListBox1.SelectedItem, True)

    End If

    wri.Close()

Dani AI

Generated

Short summary: wants to append the selected item from ListBox1 to a file and to ListBox2, but only when that item is not already present. 's pointer to use the listbox's membership check is the right idea — add a few safeguards: make sure there is a selected item, normalize/truncate whitespace, do a case-insensitive comparison (or choose the comparison that fits your requirements), and write to the file with a Using block so the writer is closed reliably.

Example Save (unique-append) — safe, compatible VB.NET pattern:

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    If ListBox1.SelectedItem Is Nothing Then
        MessageBox.Show("Please select an item first.")
        Return
    End If

    Dim newItem As String = ListBox1.GetItemText(ListBox1.SelectedItem).Trim()
    Dim exists As Boolean = False
    For Each it As Object In ListBox2.Items
        If String.Equals(it.ToString().Trim(), newItem, StringComparison.OrdinalIgnoreCase) Then
            exists = True
            Exit For
        End If
    Next

    If exists Then
        MessageBox.Show("This item already exists in ListBox2.")
        Return
    End If

    Try
        Using w As New IO.StreamWriter("E:\test.txt", True)
            w.WriteLine(newItem)
        End Using
        ListBox2.Items.Add(newItem)
    Catch ex As Exception
        MessageBox.Show("Error writing file: " & ex.Message)
    End Try
End Sub

Example Load (populate ListBox2 without duplicates):

Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
    Dim path As String = "E:\test.txt"
    If Not IO.File.Exists(path) Then Return

    For Each line As String In IO.File.ReadAllLines(path)
        Dim item As String = line.Trim()
        Dim found As Boolean = False
        For Each it As Object In ListBox2.Items
            If String.Equals(it.ToString().Trim(), item, StringComparison.OrdinalIgnoreCase) Then
                found = True : Exit For
            End If
        Next
        If Not found Then ListBox2.Items.Add(item)
    Next
End Sub

Extra notes and troubleshooting:

  • If your listboxes are bound to objects (DataSource/DisplayMember), use GetItemText(...) to get the display string instead of relying on ToString().
  • Use a user-writable folder (My Documents or AppData) rather than a root drive path to avoid permission issues.
  • If you want the file itself to never contain duplicates, read it into a HashSet (case-insensitive), add the new item there, then overwrite the file with the HashSet contents.
  • Always guard against Nothing for SelectedItem and handle IO exceptions.

try:

If listBox2.Items.Contains(listBox1.SelectedItem.ToString) Then
    MessageBox.Show("This item is in listbox 2.")
End If
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.