How to: Respond to Selecting ListBoxControl's Items
- 2 minutes to read
The ListBoxControl displays system color names. The following sample code handles the BaseListBoxControl.SelectedIndexChanged event to change the form’s background color to the color whose name is currently selected. The formBkColors hashtable is created for this purpose. Its key is a string representing the system color name. The value, in turn, represents the proper color object. Hence, when a desired color name is selected, the proper color is assigned to the form’s BackColor property.
The image below demonstrates the ListBoxControl‘s look & feel after sample code execution.
// Creates and initializes a new Hashtable.
Hashtable formBkColors = new Hashtable();
// Creates an array containing system colors
Color[] sysColors = {
SystemColors.ActiveCaption,
SystemColors.ActiveCaptionText,
SystemColors.AppWorkspace,
SystemColors.Control,
SystemColors.ControlDark,
SystemColors.ControlLight,
SystemColors.ControlText,
SystemColors.Desktop,
SystemColors.Highlight,
SystemColors.InactiveBorder,
SystemColors.InactiveCaption,
SystemColors.Info,
SystemColors.InfoText,
SystemColors.Menu,
SystemColors.MenuText,
SystemColors.ScrollBar,
SystemColors.Window,
SystemColors.WindowFrame
};
// ...
for(int i = 0; i < sysColors.Length; i++){
// Fills the hashtable
formBkColors[sysColors[i].Name] = sysColors[i];
// Populates the ListBoxControl items collection
listBoxControl1.Items.Add(sysColors[i].Name);
}
private void listBoxControl1_SelectedIndexChanged(object sender, System.EventArgs e) {
this.BackColor = (Color)formBkColors[(sender as ListBoxControl).Text];
}