Aimnox Aimnox - 5 months ago 15
Vb.net Question

How to make a listbox automatically update when the source (list) is changed

So I have a listbox with a List as a datasource. What I want is that when I add and remove items from the List, the listbox updates itself.

Right now im able to do it but in a really ugly way. What I do is remove and add the datasource in all the places that I modify the list:

For example:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
formaciones.Add(New ForDias(Formacion, NumericUpDown1.Value))
ListBox2.DataSource = Nothing
ListBox2.DataSource = formaciones
End Sub


This works, but is there any way of telling the Listbox to check again the datasource without resetting it?

Answer

You need to bind a "BindingList(of ForDias)"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim formaciones As New System.ComponentModel.BindingList(Of ForDias)
formaciones.Add(New ForDias(Formacion, NumericUpDown1.Value))
ListBox2.DataSource = Nothing
ListBox2.DataSource = formaciones
End Sub
Comments