如何在两个打开的表单之间传递值 [英] how to pass values between two opened form

查看:84
本文介绍了如何在两个打开的表单之间传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在两个打开的表单之间传递值

我有一个MDIMain Forms,因为我有两种形式.
两者都已打开,现在我必须将值从一个Child form传递给第二个Child FormTextField ,而无需创建该form的新object .
我想找到打开的form 的实例,然后传递值.

我该怎么办.

感谢您的答复

谢谢您

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

推荐答案

您可以枚举MDIMain的MDI子元素

对于每个表格,进行测试以找出是否是您想要的表格.检查我猜的表格类型吗?

要传递数据,您需要表单上的一种方法来接受数据输入.您可以从Form转换为公开方法的接口

定义接口
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
public interface ISendFormData
{
    void SendData(object data);
}



在Form2上实现接口



Implement interface on Form2

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







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;
    }
}


为什么不创建一个对应用程序全局的静态字符串值,并以两种形式使用它……
Why don''t you just create a static string value that is global to the app, and use it in both forms...


-Form1
--Form1
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



--Form2

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;
    }
}


这篇关于如何在两个打开的表单之间传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆