在C#中的参数传递来回形式之间 [英] Passing Parameters back and forth between forms in C#

查看:122
本文介绍了在C#中的参数传递来回形式之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个应用程序,用户会点击Form1上的一个按钮,这将导致窗体2显示。然后,用户将填写一个聊天Form2上,然后点击一个按钮,将关闭2并发送回参数到Form1进行处理。我怎样才能做到这在C#?我已经看到了使用属性来做到这一点的人,但这些例子不够清晰。能有人给我展示我如何可以传递参数的一些示例代码?我宁愿特性的方法,但只要它的作品,我会指望它作为回答。

I am creating an application where a user will click a button on form1, which will cause form2 to display. The user will then fill out a chat on form2 and then click a button that will close form2 and send back parameters to form1 for processing. How can I do this in C#? I have seen people using properties to do this, but the examples are not clear enough. Can someone give some example code showing me how I can pass the parameters? I would prefer the properties method, but as long as it works, I will count it as the answer.

推荐答案

简单地说,把你的表单元素的第二种形式按照通常的做法。然后,您可以访问公共添加到表格,你可以再从和参考拉。例如,如果窗体2有你想拉回来一个文本框,您可以:

Put simply, place your form elements in the second form as you typically would. Then, you can add public accessors to that form that you can then pull from and reference. For instance, if Form2 has a text fields you wanted to pull back, you could:

class Form2
{
  // Form2.designer.cs
  private TextBox TextBox1;

  // Form2.cs
  public String TextBoxValue // retrieving a value from
  {
    get
    {
      return this.TextBox1.Text;
    }
  }

  public Form2(String InitialTextBoxValue) // passing value to
  {
    IntiializeComponent();

    this.TextBox1.Text = InitialTextBoxValue;
  }
}



然后,只需访问后,当您创建表单(很像的OpenFileDialog确实为文件名等。

Then just access it later when you create the form (much like the OpenFileDialog does for Filename etc.

public void Button1_Click(object sender, EventArgs e)
{
  Form2 form2 = new Form2("Bob");      // Start with "Bob"
  form2.ShowDialog();                  // Dialog opens and user enters "John" and closes it
  MessageBox.Show(form2.TextBoxValue); // now the value is "John"
}

相同事情可以的Int32,布尔等做只是取决于窗体的值,如果你想投/验证它,否则。

Same thing can be done for Int32, Boolean, etc. Just depends on the form's value, if you'd like to cast/validate it, or otherwise.

Alternativly,你可以用窗体设计器中的修饰符属性发挥在那里你可以使控制公共所以它的外部访问。我个人推荐使用的访问,所以你可以验证并确认返回的结果而不是仅仅倾销值(这个逻辑在形式本身通常发现的,而不是你想调用/使用Form2的每个实例)

Alternativly, you can play with the Modifiers property within the form designer where you can make the control public so it's accessible externally. I personally recommend using an accessor so you can validate and confirm the returned results rather than just dumping the value (as this logic is typically found in the form itself, not in every instance you want to call/use Form2)

这篇关于在C#中的参数传递来回形式之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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