Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to pass the value one form to another form in Windows Form Application using C#?
Posted
Updated 6-Nov-11 0:14am
v4
Comments
BillWoodruff 6-Nov-11 0:06am    
Unless we know how your Forms are created ... design-time ? ... run-time ? And what instantiates your Forms ... a third Form ? One of the two Forms creates an instance of the other after itself has been instantiated ?

And until we know what you mean by passing a "Value" ... an Object, an Interface, a 'piece of data like a number or string ... ?

I don't believe we can respond meaningfully ... as possible ... to your question. One-size does not fit all here.

Oh well, forget that :), I'm going to add an answer of another type anyway.

This is the popular question about form collaboration. The most robust solution is implementation of an appropriate interface in form class. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].

—SA
 
Share this answer
 
Comments
BillWoodruff 6-Nov-11 1:35am    
+5 Hi SAK, I have studied your response to Sergiu's question on April 13, 2011, that you link to here.

And, I thank you for having directed my attention to the use of objects cast to an Interface as a way to expose a selected object, or range of objects, across Class boundaries, in both that post, and this one.

There remain, for me, and perhaps others ... who (like me ?) "locked on" to Interfaces as "contracts" and did not appreciate until some time later their other very useful functionality ? ... some "gray areas" where I (perhaps others ?) would enjoy/appreciate detailed response/advice from you.

With your "blessing" I'd like to post a broader question on the C# forum citing your two comments, and with a working source-code example of this type of use of interface ... accompanied by an invitation for comment and critique, and alternative, or best, practices for using Interfaces for information exchange across Classes/Forms, etc.

Or, if there's some way I can send a small C# project to you, as an example of how I now interpret your suggestions, and you may be perhaps be inspired to write a tip/trick ... illustrating best practice ... perhaps critiquing my example and illustrating its deficiencies ... that would be great.

What do you think ? I love to think of work other people can do :)

best, Bill
Sergey Alexandrovich Kryukov 6-Nov-11 10:21am    
Thank you, Bill.
If you want to collaborate this way, we can try. You can write to me directly via my Web site's "Contact me" form, and optionally you can post a zip file with the message. My site is visible in my CodeProject profile page.
--SA
DaveyM69 6-Nov-11 9:50am    
Hi SAK, I have seen this answer of yours before and not responded as I wanted to ponder on your suggestion. However, I'm still having difficulty in seeing the benifit of using an interface over setting a property or sending a custom EventArgs depending on the direction of communication.
Interfaces are normally more suited to a particular functionality (eg IComparable) or a representation of a common object where an abstract class is not desired. While they can be used in this situation I'm not sure what we gain when passing discrete values. In fact, to ensure only the relavent data is available in a complex object such as a form we would need to create and implement many small interfaces so we only pass the interface that has the particular data required.
Sergey Alexandrovich Kryukov 6-Nov-11 12:43pm    
You can use the other approach of course. Let me review your notes.

1) "to a particular functionality"; I don't see why "particular" and not "universal" or "general", but the situation with two form are more "particular" then others, practically, "ad hoc" situation; you could criticize my approach for using very fundamental method to ad-hoc situation, but I would not understand why such "philosophy" could be taken into consideration. The solution requires convenience, simplicity, robustness, safety and maintainability (first of all); how "particular" or not is relevant?

2) "where an abstract class is not desired". Irrelevant because form classes are not abstract already.

3) "I'm not sure what we gain when passing discrete values". Strange. Interfaces are interfaces. There methods or properties can pass anything at all. What do you want to "gain"? You want to pass values -- nice, pass them.

4) "we would need to create and implement many small interfaces so we only pass the interface that has the particular data required". Do not reduce the idea an absurd. No. You can implement only one or, say, two. Nothing prevents you from putting all you need in one interface, meaning of it would be, say, "access to a form from other forms". You still have a benefit of passing only the interface to precisely limited functionality.

I would also add that event approach is not alternative to interfaces. Even if you use the event; do you want to limit access to a form form other forms? You are not doing it with just event/delegate; would pass the reference to a form. If you want it, you still need an interface, which can include event/delegage; but why adding an event/delegate if you already can do it in interface methods/properties? You note on multiple interfaces actually applies only to your event/delegate approach; you would really need many. With interfaces, one is enough.

Best thing with this approach is its convenience. It only looks good when paired with partial class declarations in different files.

--SA
DaveyM69 6-Nov-11 14:53pm    
"Do not reduce the idea an absurd. No. You can implement only one or, say, two." This is the bit that concerns me most. In the property or event convention, when something changes we generally set a property to a single type of value or raise an event with data of a single value - we don't pass the entire object. You on the other hand are saying to pass an entire interface with possibly many properties (or keeping a constant reference to one - I understand a delegate does this too) every time just one value has changed.

If only one thing has changed or is about to change etc, that should be the only information presented/passed IMO, there is no need for an entire interface to be given each time.

I don't disagree that yours is a convenient approach and will work well, I just fail to see any advantage over the traditional and widely used approaches that are quite adequate for all situations.

I will experiment with it however, and if you and Bill do collaberate, please let me know as I would be very interested to see exactly how you implement this in a real world situation :-)
There are different ways to do this.
One is using a Property on one of your Forms.
C#
MyForm frm = new MyForm();
// It is possible to set MyValue at any point in your code, as long as you have a reference to an instance of MyForm.
frm.MyValue = "some value";
frm.Show();

Another is passing it to the constructor.
C#
public partial class MyForm : Form
{
   private String _myValue;
   public Form1(String myValue)
   {
      InitializeComponent();
      _myValue = myValue;
      // Possibly use myValue here.
   }
   // Do stuff with _myValue here.
}
Usage would look like this:
C#
MyForm frm = new MyForm("some value");
frm.Show();

Another approach could be to use a Method...
C#
public partial class MyForm : Form
{
   private String _myValue;
   public void SetValue(String myValue)
   {
      _myValue = myValue;
     // Possibly do stuff with myValue here.
   }
   // Or use _myValue here.
}
Usage:
C#
MyForm frm = new MyForm();
frm.Show();
// Once again, you can use this anywhere in your code, as long as you have a reference to the instance of MyForm.
frm.SetValue("some value");
Hope it helps! :)
 
Share this answer
 
Well, For the solution of this problem, I like to follow one of the following two methods:

Method 1: Using Constructor

First assume there are two forms Form1 and Form2. You want to pass any value from Form1 to Form2. Simply use the constructor of Form2 to pass it on. Then you have to define the constructor of Form2 like this:

C#
public Form2(String anyValue)
{
    Value=anyValue;
    //do whatever you want
}


Declare a global variable (here Value) to receive the passed value and use it in Form2 wherever you want.

In Form1: you call Form2 like this:

C#
Form2 frm2=new Form2(anyStringValue);
frm2.Show();
//do else


Method2: Using Encapsulation Capability/Property.

Assume you want to pass a string value from Form1 to Form2. First in Form2 declare a global variable of type String, then encapsulate it.

C#
String receivedValue;

Now encapsulate this field (assuming that you know how to encapsulate a field). It should look like this:
C#
public String ReceivedValue
        {
            get { return receivedValue; }
            set { receivedValue = value; }
        }


From Form1 while calling Form2 use encapsulated field/property to pass data.

C#
Form2 frm2=new Form2();
frm2.ReceivedValue=_any_Value_From_Form1;
 
Share this answer
 
v3
It depends on the hierachy of the forms.

A parent can pass data to a child via a property or method defined in the child.
A child can signal to the parent that it has data it might be interested in by raising an event that that is defined in the child which the parent subscribes to.
A sibling can pass data to a sibling via it's parent who acts as a controller: ChildEvent -> Parent -> ChildProperty/ChildMethod.

The constructor parameter way is almost always a bad idea!

These tips/articles may be useful:
Pass value between forms using events[^]
Basic Event Creation in C#[^]
Events Made Simple[^]
 
Share this answer
 
Comments
BillWoodruff 5-Nov-11 23:26pm    
I have 5'd your answer because you at least cared to imply that this question has been asked and answered many times, and gave links.

However, I think talking about Parent/Child relationships with Forms is a bit distracting here, since in WinForms that has other meanings than inheritance (which I consider a flaw in WinForms syntax, by the way).
Create properties to the form that is going to be accessed to another form.
 
Share this answer
 
Well, as long as we're offering a 'buffet' of all types of solutions on this thread ... I might as well serve one up with a different flavor, a 'static' flavor, but I hope still slightly tasty :)

Another way to approach this information transfer across Classes/Forms is by use of a 'static' class that encapsulates information transfer. It might look like this:
C#
// requires a reference to using System.Windows.Forms;

public static class ListBoxItemManager
{
    public static ListBox ListBoxOnForm1;

    public static ListBox ListBoxOnForm2;

    public static void  CopyListForm1ToForm2()
    {
        ListBoxOnForm2.Items.Clear();

        foreach (var lbItem in ListBoxOnForm1.Items)
        {
            ListBoxOnForm2.Items.Add(lbItem);
        }
    }
}
So, how do the references ... in the static class ... to the actual ListBoxes on the actual instances of Form1 and Form2 get assigned ?

In Form1 like this:
C#
//note in this example an instance of Form2 is created in Form1

private Form2 f2;

private void Form1_Load(object sender, EventArgs e)
{
    ListBoxItemManager.ListBoxOnForm1 = listBox1;

    // instantiating f2 here will invoke Form2's Load Event
    f2 = new Form2();
    f2.Show();
}
And, in Form2's Load Event:
C#
private void Form2_Load(object sender, EventArgs e)
{
    // note there's no semantic confusion here:
    // both Forms happen to have ListBoxes named 'listBox1
    ListBoxItemManager.ListBoxOnForm2 = listBox1;
}
So how does the instance of Form1 trigger the copying of its ListBox's items to the ListBox on Form2: assume a Button on Form1, named 'button1' :
C#
private void button1_Click(object sender, EventArgs e)
{
    ListBoxItemManager.CopyListForm1ToForm2();
}
Discussion:

1. obviously this highly specific example could be made much more general: what is now the 'CopyListForm1ToForm2' method in the static class could take one ListBox as a parameter, and be made a two-way copying facility. Or, with multiple ListBoxes on multiple Forms, the 'CopyListForm1ToForm2' method in the static class could take two parameters: a source ListBox, and a destination ListBox, etc.

... begin edit #1 ... in response to a friendly suggestion that I demonstrate how easy it is to extend this type of solution ...
C#
public static void CopyList(ListBox sourceListBox)
{
    ListBox targetListBox = sourceListBox == ListBoxOnForm1 ? ListBoxOnForm2 : ListBoxOnForm1;

    targetListBox.Items.Clear();

    foreach (var lbItem in sourceListBox.Items)
    {
        targetListBox.Items.Add(lbItem);
    }
}
So here the ListBoxItemManager static class has a method added that takes a ListBox as a parameter, and 'does the right thing' to copy from the parameter specified ListBox to the 'other' ListBox.

It could be called from Form1 like this to copy the ListBox Items from Form2's ListBox to Form1's ListBox:
C#
private void button1_Click(object sender, EventArgs e)
{
    ListBoxItemManager.CopyList(ListBoxItemManager.ListBoxOnForm2);
}

... end edit #1 ... of course this code could be refactored, simplified !

2. in fact, I would only use this type of technique where there would probably be much more complex interaction required between forms, and when there would be interaction required between, perhaps, multiple instances of different types of Forms. Or, in scenarios where multiple events being raised from multiple Forms might need to be "dipatched."

One-size does not fit all: make sure you try walking more than a few steps in any pair of new shoes :)
 
Share this answer
 
v2
We can pass value from one form to another using constructor
See the below link for more details:
Passing values from one form to another using constructor
 
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