Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
How to pass the value one form to another form in Windows Form Application using C#?
Posted 5-Nov-11 5:02am
Sam Path1.7K
Edited 6-Nov-11 1:14am
v4
Comments
BillWoodruff at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

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
  Permalink  
Comments
BillWoodruff at 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
SAKryukov at 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 at 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.
SAKryukov at 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 at 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 :-)
SAKryukov at 7-Nov-11 9:31am
   
I have an impression that you simply do not understand something or cannot picture it all. See: "we don't pass the entire object... every time just one value has changed". What are you talking about? Passing interface is not a "change". Before you do something related to form collaboration you pass a reference to the instance of the form to the instance of other form. With interface, you pass the instance of the same form but in the form of interface. After that, another form stored this reference for a long time, but with interface the exposed members are limited and/or encapsulated. "Changing value" and other stuff happen when one form actually uses interface reference to other form for actual calls (and in particular, add/remove handlers to events). Again, I got a strong impression than you may be fail to understand how interfaces work. This is really not so trivial mechanism; so some misunderstanding is usual.
 
If you still fail to see the benefit, I don't what to say, I already explained it all, maybe it needs illustration with the code. Also, it depends on scale; in simple applications, stronger isolation between forms may be not so important as the project is manageable enough just due to its small size.
 
--SA
DaveyM69 at 7-Nov-11 16:05pm
   
Forgive me if I sound rude but I am perfectly clear on how interfaces work! Don't assume that because I'm not understanding you fully that my knowledge is lacking in the language fundementals.
 
It seems I may have misunderstood, you see this as an alternative for passing entire form instance references? I rarely pass an entire form and certainly wouldn't to facilitate the communication of one value as the OP wanted. I use the event/delegate method for this (or keep a reference in the owner) and was trying to understand how your interface fitted into this - the answer is it doesn't. You are simply using an interface (as a parameter to a constructor or similar I assume) to couple the forms as a slightly better alternative to coupling to a specific concrete implementation of a form.
 
Tight coupling of this kind, even if done with an interface, is something I avoid wherever possible.
 
Edit: I assume you mean something like this...
public interface IOwner
{
void SetText(string text);
}
 
public partial class FormMain : Form, IOwner
{
public FormMain()
{
InitializeComponent();
}
 
public void SetText(string text)
{
Text = text;
}
}
 
public partial class FormOther : Form
{
private IOwner owner;
 
public FormOther()
: this(null)
{ }
public FormOther(IOwner owner)
{
InitializeComponent();
this.owner = owner;
}
 
private void SetOwnerText(string text)
{
if (owner != null)
{
owner.SetText(text);
}
}
}
NandaKumer at 7-Nov-11 0:21am
   
good answer
SAKryukov at 7-Nov-11 0:25am
   
Thank you, Nanda.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

There are different ways to do this.
One is using a Property on one of your Forms.
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.
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:
MyForm frm = new MyForm("some value");
frm.Show();
Another approach could be to use a Method...
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:
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! Smile | :)
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

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:
 
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:
 
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.
 
String receivedValue;
Now encapsulate this field (assuming that you know how to encapsulate a field). It should look like this:
public String ReceivedValue
        {
            get { return receivedValue; }
            set { receivedValue = value; }
        }
 
From Form1 while calling Form2 use encapsulated field/property to pass data.
 
Form2 frm2=new Form2();
frm2.ReceivedValue=_any_Value_From_Form1;
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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[^]
  Permalink  
Comments
BillWoodruff at 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).
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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 Smile | :)
 
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:
// 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:
//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:
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' :
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 ...
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:
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 Smile | :)
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

Create properties to the form that is going to be accessed to another form.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 8

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
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 299
1 Maciej Los 295
2 Sergey Alexandrovich Kryukov 230
3 Aajmot Sk 191
4 Sinisa Hajnal 166
0 OriginalGriff 7,760
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,785


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 27 Feb 2012
Copyright © CodeProject, 1999-2014
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