I have an small (probably dumb) issue with databinding. I try to bind a List
List<double> _measuredValues = new List<double>();
to a winforms ListBox.
In Form_Load I set:
lstMeasuredValues.DataSource = _measuredValues;
When I update the values, nothing appears?!
_measuredValues.Add(numBuffer);
One thing I thought about is a data type issue. But how do I change the type just to change it into a string?
lstMeasuredValues.DataSource = _measuredValues.ToString().ToList();
Another reason might be that the upper line of code is within another thread. But I think this should not be the problem.
How can I bind this list?
In order to allow UI to reflect the data source modifications, the data source must provide some sort of a change notification. WinForms list data binding infrastructure uses ListChanged event of the IBindingList Interface. There is a standard provided BindingList<T> class which can be used instead of
List<T>
to get the desired behavior. All you need is changing this lineto
That's not good. You must make sure you don't do that because
ListChanged
event is expected to be raised on the UI thread.The problem is that the common
List
isn't the right choice for data binding. You should use BindingList if you want to keep updated the ListBox.Try using it this way:
Keep in mind that when you add a new item in _measuredValues you have to manually refresh the binding, as far as I now, like this:
All you need to do it to refresh the list after updating:
The better way is to clear the items and assign the DataSource again:
Or even you can define your own refresh function and call like the following:
And call them when ever you need to refresh the list:
One of the simplest way to do it is by putting:
Whenever your
_measuredValues
element is updatedYou could use a
BindingList<double>
as DataSource of your ListboxNow everytime you need to add an element use the bindList variable and your listbox will update automatically as well as your
_measuredValues
list