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

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

问题描述

我正在创建一个应用程序,用户将在其中单击 form1 上的按钮,这将导致显示 form2.然后,用户将在 form2 上填写聊天内容,然后单击将关闭 form2 并将参数发送回 form1 进行处理的按钮.我怎样才能在 C# 中做到这一点?我见过有人使用属性来做到这一点,但例子不够清楚.有人可以给出一些示例代码,向我展示如何传递参数吗?我更喜欢properties方法,但只要它有效,我就会把它当作答案.

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.

推荐答案

简而言之,像往常一样将表单元素放在第二种表单中.然后,您可以向该表单添加公共访问器,然后您可以从中提取和引用.例如,如果 Form2 有一个您想要撤回的文本字段,您可以:

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、Boolean 等做.只取决于表单的值,如果你想转换/验证它,或者其他.

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.

或者,您可以在表单设计器中使用 Modifiers 属性,您可以在其中将控件设为公开,以便可以从外部访问.我个人建议使用访问器,以便您可以验证和确认返回的结果,而不仅仅是转储值(因为此逻辑通常在表单本身中找到,而不是在您想要调用/使用 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天全站免登陆