karan sharma karan sharma - 2 months ago 22
C# Question

copying items of one listbox to another

I want to copy listbox items from one form to another....actually in the 1st form I have 2 listboxes and in the 2nd form I also have 2 listboxes. I want to move the items of the 1st form's listboxes to 2nd form..... please help me....

Answer
public partial class Form1 : Form
{
    List<String> mylistSource;

    public Form1()
    {
        InitializeComponent();
        mylistSource = new List<string>();
        // populate source with test data
        for (int i = 0; i < 25; i++)
        {
            mylistSource.Add(i.ToString());
        }

        //assign source to both lists
        listBox1.DataSource = mylistSource;
        listBox2.DataSource = mylistSource;
    }
}

Just add 2 listboxes to a form and paste in code to run.

or if you just want to copy selected items you can simply do this:

foreach (var item in listBox1.SelectedItems)
{
    listBox3.Items.Add(item);
}