0

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
Aimnox
  • 895
  • 7
  • 20
  • 1
    Use a `BindingList` or `ObservableCollection` instead of a plain List. The differences of both methods are well explained [here](http://stackoverflow.com/a/4284805/2882256). – Alex B. Jun 30 '16 at 09:51

1 Answers1

1

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
  • It worked perfectly, ty. Now im strugling to filter it. The `where` returns me a IEnumerable, that i can convert to a new binding list. I can then bind the ListBox to it. Is there any way of doing it without creating a new binding list each time? – Aimnox Jun 30 '16 at 10:40
  • @Aimnox can you paste the code of your filter please? – Alex B. Jun 30 '16 at 11:23
  • @AlexB. Added the filter – Aimnox Jun 30 '16 at 11:33
  • @Aimnox The filter was correct except the BindingList should be casted to ForDias: `ListBox2.DataSource = New BindingList(Of ForDias) ...`. This seems to be the convenient way of filtering BindingLists, according to some linkes like [here](https://social.msdn.microsoft.com/Forums/vstudio/en-US/cb7e21ec-4ac9-45ec-824a-e527d194c97c/filtering-a-binding-list?forum=csharpgeneral). – Alex B. Jun 30 '16 at 12:25
  • @Alex The problem is that for compatibility with other parts I need formaciones to be of object. So the binding list needs to be the same – Aimnox Jun 30 '16 at 12:51