C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
MainWindow: This Form has a member variable of the List generic type. 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 autogenerated by the Designer.
partialConstructor: The code assigns to the DataSource. The DataSource property is assigned to the List member variable.
ConstructorExample that sets DataSource property: C#
public partial class MainWindow : Form
{
List<string> _sideList = new List<string>();
public MainWindow()
{
InitializeComponent();
sideListBox1.DataSource = _sideList;
}
}
Next: Here is a custom method that prepends a string to the top of the control, and then makes it display.
InsertString: 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();
}
Example that calls method: C#
void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// ... Show some results from the BackgroundWorker task.
AddListLine("5000 games: " + (string)e.Result);
}
Thus: These properties together result in an interface that is versatile and easily maintained.