如何从C#中的形式返回一个值? [英] How to return a value from a Form in C#?
问题描述
我有一个主表(让我们称之为frmHireQuote),这是一个主要的MDI窗体(frmMainMDI),这显示了另一种形式(frmImportContact)通过ShowDialog的()单击一个按钮时,一个孩子
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?
推荐答案
在子表单创建一些公共属性像这样
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.Close();
}
然后在 frmHireQuote形式,当您打开子窗体
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;
}
}
Additionaly如果你想抵消分形式你可以添加一个按钮的形式,并设置其<一个href="http://msdn.microsoft.com/en-GB/library/system.windows.forms.button.dialogresult.aspx">DialogResult以取消
,你还可以设置<一个href="http://msdn.microsoft.com/en-GB/library/system.windows.forms.form.cancelbutton%28v=vs.80%29.aspx">CancelButton表格的属性来表示按钮 - 这将使ESC键,取消表单的
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屋!