简体   繁体   English

forms之间如何进行数据通信?

[英]how to communicate data between forms?

I want to pass some values to different forms at there button click event.我想在按钮单击事件中将一些值传递给不同的 forms。 plz guide me.I am using c sharp.net 2005,win forms.请指导我。我正在使用 c sharp.net 2005,赢得 forms。 I want to access the value in a sql query in form 2 received from form 1 variable.我想访问从表格 1 变量接收的表格 2 中的 sql 查询中的值。

Use delegate.使用委托。 Thats the best way you could talk.那是你说话的最好方式。 Or as suggested, if form2 is a child of form1, then ctor argument based.或者如建议的那样,如果 form2 是 form1 的子级,则基于 ctor 参数。 If its 2 independent, then delegates.如果其 2 独立,则代表。

You have several options:你有几个选择:

  • pass the data to the constructor of the child form将数据传递给子窗体的构造函数
  • expose a instance property in the parent form, then pass that form as an argument to the child form在父表单中公开一个实例属性,然后将该表单作为参数传递给子表单
  • expose a static property in the parent form在父窗体中公开 static 属性

You can pass it through the constructor of the child form if the data is mandatory, or through a property if it is optional.如果数据是必需的,则可以通过子表单的构造函数传递它,如果是可选的,则可以通过属性传递。

Try this code, you have to do something like following code: inside this event you have to pass data to other试试这个代码,你必须做类似下面的代码:在这个事件中,你必须将数据传递给其他

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 secondForm = new Form2();
        secondForm.YourProperty = "This is your data";
        secondForm.Show();
    }

In the other form you have to declare a property:在另一种形式中,您必须声明一个属性:

    public string YourProperty { get; set; }

hope this help.希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM