190 likes | 197 Views
Learn how to use the ListBox control in Microsoft Visual C# .NET, including displaying a list of items, adding or removing items at design time or runtime, and selecting multiple items.
E N D
Chapter 9 Programming Based on Events Microsoft Visual C# .NET: From Problem Analysis to Program Design
ListBox Control Objects • Displays list of items for single or multiple selections • Scroll bar is automatically added when total number of items exceeds the number that can be displayed • Can add or remove items at design time or dynamically at runtime • Includes number of properties and events • Items property used to set initial values • Click on (Collections) to add items
Adding a ListBox Control Object Add ListBox control, then click on Items property (Collection) to type entries
ListBox Control Objects (continued) • Name property • Useful to set for program statements • Sorted property • Set to true to avoid having to type values in sorted order • Register an event for the ListBox • Might want to know when the item selection changes • Double-clicking on any control registers its default event for the control • SelectedIndexChanged—default event for ListBox
ListBox Control Objects (continued) • Register its event with the System.EventHandler delegate this.lstBoxEvents.SelectedIndexChanged += new System.EventHandler (this.listBox1_SelectedIndexChanged); • Visual Studio .NET adds event handler method private void listBox1_SelectedIndexChanged (object sender, System.EventArgs e) { }
ListBox Control Objects (continued) • To retrieve string data from ListBox use Text property this.txtBoxResult.Text = this.lstBoxEvents.Text; • Place in method body • When event fires, selection retrieved and stored in TextBox object
Multiple Selections with a ListBox • SelectionMode Property has values of MultiSimple, MultiExtended, None and One • MultiSimple: use the spacebar and click of mouse • MultiExtended can also use Ctrl key, Shift key, and arrow keys foreach(string activity in lstBoxEvents.SelectedItems) { result += activity + " "; } this.txtBoxResult.Text = result;
ListBox Control Objects (continued) • SelectedItem and SelectedItems returns objects • Store numbers in the ListBox, once retrieved as objects, cast the object into an int or double for processing • Adding items to a ListBox at runtime by using Add( ) method with the Items property lstBoxEvents.Items.Add("string value to add"); privatevoid btnNew_Click(object sender, System.EventArgs e) { lstBoxEvents.Items.Add(txtBoxNewAct.Text); }
Methods of the ListBox Class Remember ListBox object also inherits members from Control class
Methods of the ListBox Class Remember ListBox object also inherits members from Control class