DataSource
The C# DataSource
property allows data binding on Windows Forms controls. With it we bind an array to a ListBox
on the screen—and display all the strings.
A key benefit to data binding (as with DataSource
) is instant updates. As changes are made to the List
, the control on the screen is rendered with the new data.
A ListBox
control has a DataSource
property that can be assigned a value. You can assign a collection to it. Collections include arrays, Lists and DataTables
.
List
member variable. This will be where we want to store the strings that will show on the ListBox
.class
and InitializeComponent
were generated by the Designer.DataSource
. The DataSource
property is assigned to the List
member variable.public partial class MainWindow : Form
{
List<string> _sideList = new List<string>();
public MainWindow()
{
InitializeComponent();
sideListBox1.DataSource = _sideList;
}
}
BindingContext
Here is a custom method that prepends a string
to the top of the control, and then makes it display. BindingContext
is used to force a display.
Insert()
method receives a string
and then Inserts it to the start of the member List
, and then forces the ListBox
to refresh.CurrencyManager
and then Refreshes the ListBox
.CurrencyManager
type, the word Currency refers to current. It is used to ensure a control is current.private void AddListLine(string lineIn)
{
// ... Insert the string at the front of the List.
_sideList.Insert(0, lineIn);
// ... Force a refresh of the ListBox.
((CurrencyManager)sideListBox1.BindingContext[_sideList]).Refresh();
}
We used the DataSource
property on a ListBox
control in Windows Forms. CurrencyManager
and Refresh()
can be used to force a ListBox
to display.