Home
Map
DataSource ExampleUse the DataSource property in Windows Forms. With this property, the code updates elements in a ListBox.
WinForms
This page was last reviewed on Jun 14, 2023.
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.
Data binding benefits. 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.
Example. 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.
Detail This Form has a List member variable. This will be where we want to store the strings that will show on the ListBox.
Note The constructor and the partial class and InitializeComponent were generated by the Designer.
Detail The code assigns to the 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.
Info The Insert() method receives a string and then Inserts it to the start of the member List, and then forces the ListBox to refresh.
Detail The syntax at the end does a cast and a lookup to get the CurrencyManager and then Refreshes the ListBox.
Tip In the 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(); }
A summary. We used the DataSource property on a ListBox control in Windows Forms. CurrencyManager and Refresh() can be used to force a ListBox to display.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 14, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.