Listbox Updated Event

Mosteck

Active member
Joined
Nov 23, 2008
Messages
31
Location
Toronto
Programming Experience
3-5
I'm writing status messages to a listbox using the item.add("XXX") command which appends the existing list whenever something happens (for example, receives data from a socket).

I would like to have the last item selected using the listbox.selectedindex = listbox.items.count - 1 so that the listbox keeps scrolling down with the data added.

Is there an event that monitors the change in the listbox count so it happens automatically? I just don't want to add a routine to each location I add data to the listbox.

Thanks!
 
None that I know of, but you can make a sub that accepts the text to be added to the listbox and in this sub add the item and do the selectedindex = thing there, granted you'd have to change all of the spots that adds something to the listbox but it'd make future development easier
 
Thanks, I ended up just adding a timer.tick event that checks it... Just thought it would be better if there was an event that fired.

Thanks...
 
Last edited:
So you're going to have a timer ticking all the time even when nothing is added to the ListBox? Not only is this a waste of resources but what if you click on another item further up (or even scroll up)? You do realize that the timer will over ride that even though no data's added.

This is why I recommended making a sub to add items to the ListBox.
 
Yes, I agree with you... But this is just a status window, not a user selection window. I'm also limiting the number of displayed items in the textbox.

Thanks for the advise...
 
Use a list collection that has event notification for changes, like the BindingList(Of T), you just bind this to the ListBox.DataSource. When adding items you add them to the data list and not the display box. Listen for its ListChanged event. Here is some sample code that implements the ideas discussed:
VB.NET:
Private WithEvents bindlist As New BindingList(Of String)
 
Private Sub testForm1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.ListBox1.DataSource = bindlist
End Sub

Private Sub AddButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddButton.Click
    Static count As Integer
    count += 1
    bindlist.Add(count.ToString)
End Sub

Private Sub bindlist_ListChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ListChangedEventArgs) Handles bindlist.ListChanged
    If e.ListChangedType = ListChangedType.ItemAdded Then
        MessageBox.Show(bindlist.Item(e.NewIndex) & " was just added.")
    End If
End Sub
EDIT, scratch that actually, this won't work for your TopIndex thing, because the control has not been updated with the list change yet, and when it does it resets all selections. So go for the method way.
 
Back
Top