Following example show how to add and remove items in ListBox control at runtime.
This example requires two ListBox controls Named ListBox1 and ListBox2, and two button control with name ButtonSelect and ButtonDeselect, arrange these control on the windows form such as:
When we click on Button Select then Selected item of ListBox1 will be add to ListBox2 after removing from ListBox1 control.And we clcik on ButtonDeselect then selected item of Listbox2 will go to ListBox1 again.
Code:
private void BindListBox1() { ListBox1.Items.Add("New Delhi"); ListBox1.Items.Add("Tokyo"); ListBox1.Items.Add("Newyork"); ListBox1.Items.Add("Sydney"); ListBox1.Items.Add("Paris"); ListBox1.Items.Add("Londan"); }
private void ButtonSelect_Click(System.Object sender, System.EventArgs e) { if (ListBox1.SelectedItem != null) { ListBox2.Items.Add(ListBox1.SelectedItem); ListBox1.Items.Remove(ListBox1.SelectedItem); } } private void ButtonDeselect_Click(System.Object sender, System.EventArgs e) { if (ListBox2.SelectedItem != null) { ListBox1.Items.Add(ListBox2.SelectedItem); ListBox2.Items.Remove(ListBox2.SelectedItem); } }