Windows Application - SPLessons

Win App List Box Control

Home > Lesson > Chapter 10
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Win App List Box Control

Windows Application List Box Control

List Box

shape Description

List Box Control is a control which is used to display the list of items and also used for Add/Remove items from the list with the help of buttons.

shape Examples

Following is a simple windows application which is used to move items from one list box to another list box.
  • If clicked on the Move Left button, the selected will move from the second list box to first list box.
  • If clicked on Move Right button, the selected items will move from the first list box to the second list box.
Follow the bellow mentioned steps to know about the List Box Control usage.
  • Drag and drop the list box control onto the form.
  • Give a name to List box using Name property.
  • Now, add the items to the list by using items property as per rquirement.
  • Take othlist box and do same as above.
  • Take two buttons and Name them as Move Left and Move Right.
The design will look like as the following figure.    
  • Now, double click on the buttons then they raise click events.
  • Write the code under the click events as shown as below.
  [csharp] private void btnMoveRight_Click(object sender, EventArgs e) { if (listBox1.SelectedItems.Count > 0)//Checks whether item selected or not { listBox2.Items.Add(listBox1.SelectedItem);//Moves Selected item from listbox1 to listbox2 listBox1.Items.Remove(listBox1.SelectedItem);//Removes the Selected item from Listbox1 } else { MessageBox.Show("Please Select the item");//Shows an error message, if no item get selected } } private void btnMoveLeft_Click(object sender, EventArgs e) { if (listBox2.SelectedItems.Count > 0)//Checks whether item selected or not { listBox1.Items.Add(listBox2.SelectedItem);//Moves Selected item from listbox2 to listbox1 listBox2.Items.Remove(listBox2.SelectedItem);//Removes the Selected item from Listbox2 } else { MessageBox.Show("Please Select the item");//Shows an error message, if no item get selected } }[/csharp]
  • Press F5 or Start to run the application.
  • Then the output will be display as shown in the below figure.
   
  • Select any item in the first list box and click on the Move Right button. Then the selected item will move to the second list box control and also will remove from the first list box.Below figure shows moving of items from the first list box to the second list box.
   
  • Select any item in the second list box and click on the Move left button. Then the selected item will move to the first list box control and also will remove from the second list box.Below figure shows moving of items from the first list box to the second list box.
    If no item gets selected, then the messages box will show an error message. Without selecting any item, press any button. Then, it will show an error message as shown in the below figure.