如何从 C# 中的表单返回值? [英] How to return a value from a Form in C#?

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

问题描述

我有一个主窗体(我们称之为 frmHireQuote),它是主 MDI 窗体 (frmMainMDI) 的子窗体,当单击按钮时,它通过 ShowDialog() 显示另一个窗体 (frmImportContact).

I have a main form (let's call it frmHireQuote) that is a child of a main MDI form (frmMainMDI), that shows another form (frmImportContact) via ShowDialog() when a button is clicked.

当用户在 frmImportContact 上单击确定"时,我想将一些字符串变量传递回 frmHireQuote 上的一些文本框.

When the user clicks the 'OK' on frmImportContact, I want to pass a few string variables back to some text boxes on frmHireQuote.

请注意,frmHireQuote 可能有多个实例,回到调用此 frmImportContact 实例的实例显然很重要.

Note that there could be multiple instances of frmHireQuote, it's obviously important that I get back to the instance that called this instance of frmImportContact.

这样做的最佳方法是什么?

What's the best method of doing this?

推荐答案

像这样在子表单上创建一些公共属性

Create some public Properties on your sub-form like so

public string ReturnValue1 {get;set;} 
public string ReturnValue2 {get;set;}

然后在您的子表单确定按钮点击处理程序中设置它

then set this inside your sub-form ok button click handler

private void btnOk_Click(object sender,EventArgs e)
{
    this.ReturnValue1 = "Something";
    this.ReturnValue2 = DateTime.Now.ToString(); //example
    this.DialogResult = DialogResult.OK;
    this.Close();
}

然后在您的 frmHireQuote 表单中,当您打开子表单时

Then in your frmHireQuote form, when you open the sub-form

using (var form = new frmImportContact())
{
    var result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        string val = form.ReturnValue1;            //values preserved after close
        string dateString = form.ReturnValue2;
        //Do something here with these values

        //for example
        this.txtSomething.Text = val;
    }
}

此外,如果您希望取消子表单,您只需在表单中添加一个按钮并设置其DialogResultCancel,你也可以设置 CancelButton 属性以所述按钮 - 这将使退出键可以取消表单.

Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.

这篇关于如何从 C# 中的表单返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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