Aimnox
Aimnox

Reputation: 899

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?

Edit: How I filter:

On the textBox text changed event:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    ListBox2.DataSource = New BindingList(Of Object)((formaciones.Where(Function(i As ForDias) i.Formacion.ToString().Contains(TextBox1.Text))).ToList())
End Sub

Upvotes: 0

Views: 1351

Answers (1)

Sandip Patel
Sandip Patel

Reputation: 66

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

Upvotes: 1

Related Questions