Move the elements of combobox to the listbox and vice versa in C#

Description:  In this simple article you will learn that how we can move the elements of combobox to the listbox and the elements of listbox to the combobox in C#.

Insert listbox: In windows form application insert a “listbox” from toolbar in windows form.

Code:

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

{

}

Use an array to insert elements in listbox. For this create a button (show listbox). Now write the following code on Button Click event:

private void button1_Click(object sender, EventArgs e)

{

string[] myList = new string[4];

myList[0] = “Apple”;

myList[1] = “Bnana”;

myList[2] = “Grapes”;

myList[3] = “Orange”;

listBox1.Items.AddRange(myList);

}

Insert ComboBox: In windows form application insert a “combobox” from toolbar in windows form.

Code:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

{

}

Use an array to insert elements in combobox. For this create a button (show combobox). Now write the following code on Button Click event:

private void button2_Click(object sender, EventArgs e)

{

string[] mycomboList = new string[4];

mycomboList[0] = “Potato”;

mycomboList[1] = “Tomato”;

mycomboList[2] = “Onion”;

mycomboList[3] = “Peas”;

comboBox1.Items.AddRange(mycomboList);

}

AddRange function is used to manage the range of arraylist.

Move elements:

Now create a button to move elements of combobox to list box, and write the following code on button click event:

private void button4_Click(object sender, EventArgs e)

{

string move;

move = comboBox1.SelectedItem as string;

listBox1.Items.Add(move);

comboBox1.Items.Remove(move);

}

Then create a button to move elements of listbox to combobox, and write the following code on button click event:

private void button3_Click(object sender, EventArgs e)

{

string move;

move = listBox1.SelectedItem as string;

comboBox1.Items.Add(move);

listBox1.Items.Remove(listBox1.SelectedItem);

}

Add & Remove functions are used to add & remove elements from combobox to listbox and from listbox to combobox.

This simple article tells that how we can move the elements of combobox to the listbox and the elements of listbox to the combobox in C#.