Click here to Skip to main content
15,910,872 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

i wanna know how to pass listbox items from Form1 to listbox in Form2.

suppose i have two listbox one in form1 and other in form2.And a button named button1 that calls Form2.

C#
private void button1_Click(object sender, EventArgs e)
         {
             Form2 f = new Form2();
             f.Show();
         }



Now at this instance i want listbox items of form1 to be passed in listbox in form2.

Thank you
Posted
Updated 1-May-14 23:27pm
v2

Hi,

Have a look at this tip:
Transferring information between two forms, Part 1: Parent to Child[^]

In this case, you can try this:

Add a items parameter to the constructor of Form2 and copy the listbox items:
C#
public Form2(object[] items)
{
    InitializeComponent();
    listboxOnForm2.Items.AddRange(items);
}

And to pass the items from Form1 to Form2:
C#
object[] itemsToPass = new object[yourListBox.Items.Count];
yourListBox.Items.CopyTo(itemsToPass, 0);
Form2 f = new Form2(itemsToPass);
f.Show();
 
Share this answer
 
v2
Hi,

Check this link !
Passing Data Between Forms[^]
 
Share this answer
 
C#
private void button1_Click(object sender, EventArgs e)
         {
             Form2 f = new Form2("Pass your value as string");
             f.Show();
         }



and

C#
public Form2(string strValue)
   {
   InitializeComponent();
   string GetData = strValue;
   }
 
Share this answer
 
v2

  1. Create a public property on Form2 to take the data
  2. Set the property before the Show() method


e.g.

C#
//Child Form
public class Form2 : Window
{
    //snip..
    public Foo TramsferredInformation {get; set;}
    //snip..
}

//Parent Form
public class Form1 : Window
{
    //snip..
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f = new Form2();
        f.TramsferredInformation = Whatever; //Obviously, you'll need to decide what this is.
        f.Show();
    }
    //snip..
}


Foo is the type of data you want to transfer, string or some complext type etc.

Off topic, its is a bad idea to have identifiers like Form1, Form2 and the variable name "f". I assume this is just for ease of use in the question, but if not use meaningful names or you'll not be able to keep track if the project size increases or other people need to look at your code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900