Question Edit a listbox item...

newguy

Well-known member
Joined
Jun 30, 2008
Messages
611
Location
Denver Co, USA
Programming Experience
1-3
Hi All,

OK, so I am using listbox1 to send the selected.items to listbox2, when the item is sent I also want to delete the selected.items in listbox1, got it working somewhat - the only problem is it enters the item twice, once with the item(text) and DateAndTime.now and the second time with just the DateAndTime.now and no item(text).

VB.NET:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Dim int As String
        int = ListBox1.SelectedItem
        ListBox2.Items.Add(DateAndTime.Now & "  :  " + int).ToString()
        ListBox1.Items.Remove(int)
    End Sub

So listbox2 looks like...with I click of the item in listbox1...

8/30/08 830 PM : (text)
8/30/08 830 PM :
 
Last edited:
OK got it...

VB.NET:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Dim int As String
        int = ListBox1.SelectedItem
        ListBox2.Items.Add(" ( " & DateAndTime.Now & " ) : " + int).ToString()
        Dim remov As Object
        For remov = 0 To ListBox1.SelectedIndex - 1
            If ListBox1.SelectedIndex <> 0 Then
                ListBox1.Items.RemoveAt(remov)
            End If
        Next
    End Sub
 
It seems that when you are removing an item from a listbox, you raise the selectedIndexChanged a second time (you have one less item).

You can solve this problem by removing the handler to the procedure listening to the event before removing the the item, and then reasigning it.

VB.NET:
    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Dim MyValue As String = ListBox1.SelectedItem
        ListBox2.Items.Add(Date.Now)
        RemoveHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
        ListBox1.Items.Remove(MyValue)
        AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
    End Sub
 
That works great, mine still wasn't working quite right, many thanks...
 
Last edited:
Back
Top