Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
Hello,
 
I have two forms (Form1,Form2) Form1 has a listbox with items in it and a button. Form2 has another listbox. On clicking the button i need to move all the items in the listbox of Form1 to listbox of Form2. How can this be achieved in c#??
Does anyone have code snippets for the same???
Posted 12-Apr-11 1:55am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi,
passing parameters between forms is a thoroughly discussed topic. Generally, it can be done in 4 ways, using: constructor, objects, properties or delegates. Check this article for more details: Passing Data Between Forms[^]
  Permalink  
Comments
aparnask at 12-Apr-11 7:03am
   
hi i checked it out :) but the technique doesnt work for listbox :(
Olivier Levrey at 12-Apr-11 8:30am
   
You will rarely find the exact thing you want: you always need to adapt a little bit. You can use the article Ciumac gave you. For example, all items in a list box are stored in the ListBox.Items property: just pass this property from Form1 to Form2 and update your second list box with these items.
Have a 5 Ciumac.
SAKryukov at 12-Apr-11 13:44pm
   
Of course it does! you will need to abstract the collaboration mechanism your list box detail.
I advice the better method, see my Answer.
--SA
SAKryukov at 12-Apr-11 13:42pm
   
I vote 5. One method is missing! the best one in my opinion.
Please see my Answer.
Espen Harlinn at 12-Apr-11 15:23pm
   
Nice answer - 5ed!
Monjurul Habib at 6-Jun-11 16:04pm
   
nice answer,my5.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

One way of interaction between forms is missing from the Answer of Sergiu: interfaces, and this one is the most robust, in my opinion.
 
One form implements some interface known to both forms. The reference to one form is passed to another form in the form of interface instance reference. In this way, one form has no access to another form beyond the interface, which separates concerns and makes collaboration perfectly safe.
 
This is one feature which highly facilitates this: partial class declaration. In each separate partial declaration any base types are not required to be repeated in the inheritance list of each partial declaration. For example, one form file is auto-generated; and your forms inherits from System.Window.Forms.Form. It is not repeated in the other partial declaration of the same form type in the other file. Create another file! Put only the interface in the inheritance list, and implement the interface here. It will separate the aspects of the interface from other code, improving maintainability.
 
—SA
  Permalink  
Comments
Espen Harlinn at 12-Apr-11 15:24pm
   
My 5, facilitates interaction between the forms :)
Manel1989 at 27-Aug-13 10:59am
   
you explained very well , My 5
SAKryukov at 12-Apr-11 16:22pm
   
It surely does.
Thank you, Espen.
As there is nothing tricky about collaboration between form, the gain can be just in guarding against accidental mistakes and supportability benefits.
--SA
Sergey Alexandrovich Kryukov at 27-Aug-13 11:09am
   
Thank you, Manel.
—SA
Ciumac Sergiu at 13-Apr-11 2:37am
   
Yes, indeed that's a possibility. But I do prefer standard ways of interaction (maybe because I'm a big fan of delegates :) ). Anyway my 5.
SAKryukov at 13-Apr-11 2:51am
   
Thank you.
I actually think my method is better. If you want to argue in favor of delegate I would enjoy it.
What I explained is exactly as "standard" as what you suggested no more no less.
If you a fan of delegate, please tell me: if your add another handler to a delegate, does a delegate instance keep its referential identify, or a new delegate instance is created? :-)
--SA
Ciumac Sergiu at 13-Apr-11 5:35am
   
Well, I haven't tested, but it should keep it's identity. My logic is simple - each delegate class derives from MulticastDelegate which has a hidden field '_invocationList'. As far as I know that field keeps track of all function pointers to be called. Once the Invoke() or BeginInvoke() method is called, the list is iterated and every delegate in the chain is invoked. Thus I do not see why the delegate should change it's referential identity once a new handler is added (as the List object doesn't change it's identity once a new item is added to it) :)
SAKryukov at 13-Apr-11 6:09am
   
No! I found it! And later Nishant explained me why.
The new instance is created each time, that is, the event instance is not mutable, as well as string and by similar reason: thread safety. While new instance is created and invocation list is copied from old one, some thread can use the invocation list of the old one. It minimizes the time of locked part of code.
Huh? How about that?
--SA
Ciumac Sergiu at 13-Apr-11 6:52am
   
Indeed I've reread the msdn info about delegates, there is a small remark about this fact :) : "Delegates are immutable; once created, the invocation list of a delegate does not change". Useful information, thanks for sharing.
SAKryukov at 13-Apr-11 7:45am
   
My pleasure :-)
--SA
Ankur\m/ at 10-May-11 2:41am
   
5 here! :-)
SAKryukov at 10-May-11 13:08pm
   
Thank you, Ankur.
--SA
Monjurul Habib at 6-Jun-11 16:05pm
   
nice explanation, my 5.
SAKryukov at 6-Jun-11 17:44pm
   
Thank you, Monjurul.
--SA
Mika Wendelius at 20-Dec-11 17:48pm
   
Well explained, 5
SAKryukov at 20-Dec-11 17:55pm
   
Thank you, Mika.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Here is what the parent form looks like
 
using System;
using System.Windows.Forms;
using System.Collections.Generic;
namespace WindowsFormsApplication1
{
    public partial class ParentForm : Form
    {
        private Button button1;
        private ListBox listBox1;
        private ChildForm childForm = new ChildForm();
        public ParentForm()
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(94, 219);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // listBox1
            // 
            this.listBox1.FormattingEnabled = true;
            this.listBox1.Items.AddRange(new object[] {
            "item1",
            "item2",
            "item3",
            "item4",
            "item5"});
            this.listBox1.Location = new System.Drawing.Point(0, 0);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(279, 199);
            this.listBox1.TabIndex = 1;
            // 
            // ParentForm
            // 
            this.ClientSize = new System.Drawing.Size(284, 264);
            this.Controls.Add(this.listBox1);
            this.Controls.Add(this.button1);
            this.Name = "ParentForm";
            this.ResumeLayout(false);
        }
        List<String> listboxValues = new List<string>();
        private void button1_Click(object sender, EventArgs e)
        {
            listboxValues.Clear();//clear values stored in list so old value's are not resent to child form
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                listboxValues.Add((string)listBox1.Items[i]);
            }
            childForm.AddToCollection(listboxValues);
            childForm.ShowDialog();
        }
    }
}
 
and here is what the child form would look like
 
using System;
using System.Windows.Forms;
using System.Collections.Generic;
namespace WindowsFormsApplication1
{
    public partial class ChildForm : Form
    {
        private ListBox listBox1;
    
        public ChildForm()
        {
            InitializeComponent();
            
        }
        
        internal void AddToCollection(List<string> values)
        {
            for (int i = 0; i < values.Count; i++)
            {
                listBox1.Items.Add(values[i]);
            }
        }
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);
            // ensure's that list is cleared when form closes so that when form reopens the old list is not still stored in listbox
            listBox1.Items.Clear();
        }
        private void InitializeComponent()
        {
            this.listBox1 = new System.Windows.Forms.ListBox();
            this.SuspendLayout();
            // 
            // listBox1
            // 
            this.listBox1.FormattingEnabled = true;
            this.listBox1.Location = new System.Drawing.Point(0, 0);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(280, 186);
            this.listBox1.TabIndex = 0;
            // 
            // ChildForm
            // 
            this.ClientSize = new System.Drawing.Size(284, 264);
            this.Controls.Add(this.listBox1);
            this.Name = "ChildForm";
            this.ResumeLayout(false);
        }
    }
}
  Permalink  
Comments
nithikannan89 at 29-Apr-12 6:35am
   
i wanna to call an form1 function from form2 using c#, am the beginner so please your valuable suggestion.......
Thanks
Dhinesh kumar.V
JimOr at 17-Mar-14 8:22am
   
Hello,
Implimenting the above code has these errors:
 
public ParentForm()
{
InitializeComponent();
}
childForm.AddToCollection(listboxValues);
 
Not sure why , I am using C# 2010
 
Kindly,
Jim
JimOr at 17-Mar-14 8:34am
   
See Error:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private Button button1;
private ListBox listBox1;
private ChildForm childForm = new ChildForm();
public void ParentForm()
{
InitializeComponent(); // Error here,
// Error 1 The call is ambiguous between the following methods
// or properties: 'WindowsFormsApplication1.ChildForm.InitializeComponent()'
// and 'WindowsFormsApplication1.ChildForm.InitializeComponent()'
// C:\Documents and Settings\owner\my documents\visual studio 2010\Projects
// \PassingParametersBetweenforms\PassingParametersBetweenforms
// \ChildForm.cs 18 13 PassingParametersBetweenforms
 
}
 
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(94, 219);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Items.AddRange(new object[] {
"item1",
"item2",
"item3",
"item4",
"item5"});
this.listBox1.Location = new System.Drawing.Point(0, 0);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(279, 199);
this.listBox1.TabIndex = 1;
//
// ParentForm
//
this.ClientSize = new System.Drawing.Size(284, 264);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.button1);
this.Name = "ParentForm";
this.ResumeLayout(false);
}

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



Advertise | Privacy | Mobile
Web04 | 2.8.150327.1 | Last Updated 19 Apr 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100