Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to pass values between two opened form

I have One MDIMain Forms in that I have two form.
Both are opened, now I have to passed a value from One Child form to the TextField of Second Child Form without creating a new object of that form.
I want to find the instance of opened form and then pass the value.

How can I do this.

Appreciate your reply

Thanking You
Posted

You can enumerate the MDI children of MDIMain

For each form, test to find out if it's the form you want. Check for form type I guess?

To pass it data, you need a method on the form that will accept data input. You could cast from Form to an Interface that exposes a method

Define Interface
C#
public interface ISendFormData
{
    void SendData(object data);
}


Implement interface on Form2
C#
public partial class Form2 : Form, ISendFormData
{
    public Form2()
    {
        InitializeComponent();
    }
    public void SendData(object data)
    {
        // do something with the data object
    }
}



C#
foreach Form f in this.MDIChildren 
{
    Type t = f.GetType();

    if (t == typeof(Form2) && t.GetInterface("ISendFormData", true) != null)
    {
        ISendFormData myForm = (ISendFormData)f;
        myForm.SendData("Whatever you like in here!");
        break;
    }
}
 
Share this answer
 
Why don't you just create a static string value that is global to the app, and use it in both forms...
 
Share this answer
 
--Form1
C#
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    public static string CCName = "ClassCoder";
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm2 = new Form2();
        frm2.Show();
    }
}


--Form2
C#
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }
    public string CCName;
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(CCName);
    }
    private void Form2_Load(object sender, EventArgs e)
    {
        CCName = Form1.CCName;
    }
}
 
Share this answer
 
Comments
shanawazway 23-Nov-10 0:13am    
Hi,
As I mentioned in the question, I don't have to create a new object of Form.
In Form1 Button1 Click ,it is creating a new object, which create and open a new form (not MDI Child form).
It means we have to opened Forms of same name like Form, one is MDIChild Form1 and other is independent Form1.

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