Home
Search
DataSource ExampleUse the DataSource property in Windows Forms. With this property, the code updates elements in a ListBox.
C#
This page was last reviewed on Oct 6, 2022.
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.
Property
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.
Array
List
DataTable
MainWindow 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.
partial
Constructor The code assigns to the DataSource. The DataSource property is assigned to the List member variable.
Constructor
Example that sets DataSource property, C#:
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.
List Insert
String The method receives a string and then Inserts it to the start of the member List, and then forces the ListBox to refresh.
Cast 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.
Example that uses BindingContext, C#:
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 Oct 6, 2022 (grammar).
Home
Changes
© 2007-2023 Sam Allen.