如何將一個字符串從MDI父項傳遞給孩子的模態對話框?從MDI父項傳遞一個字符串到孩子的模態對話框
MDI父代碼打開孩子:
Form1 f1 = new Form1();
f1.MdiParent = this;
f1.Show();
Form1的代碼來打開模態對話框
Form2 f2= new Form2();
f2.ShowDialog();
如何將一個字符串從MDI父項傳遞給孩子的模態對話框?從MDI父項傳遞一個字符串到孩子的模態對話框
MDI父代碼打開孩子:
Form1 f1 = new Form1();
f1.MdiParent = this;
f1.Show();
Form1的代碼來打開模態對話框
Form2 f2= new Form2();
f2.ShowDialog();
如果你總是使用形式爲模式的形式,你可以使用類似的模式這個。
class FormResult
{
public DialogResult dr {get; private set;}
public string LastName {get; private set;}
public string FirstName {get; private set;}
}
class MyForm : whatever
{
static public FormResult Exec(string parm1, string parm2)
{
var result = new FormResult();
var me = new MyForm();
me.parm1 = parm1;
me.parm2 = parm2;
result.dr = me.ShowDialog();
if (result.dr == DialogResult.OK)
{
result.LastName = me.LastName;
result.FirstName = me.FirstName;
}
me.Close(); // should use try/finally or using clause
return result;
}
}
... rest of MyForm
這種模式在隔離您使用窗體的「私有」數據的途徑,並且可以很容易地 如果您決定添加MORS返回值延長。如果您有更多的一對夫婦的輸入參數,你可以捆綁它們放到一個類,並通過該類的實例來Exec方法
只是通過它通過在每個級別使用特性:
//Form1 needs a property you can access
public class Form1
{
private String _myString = null;
public String MyString { get { return _myString; } }
//change the constructor to take a String input
public Form1(String InputString)
{
_myString = InputString;
}
//...and the rest of the class as you have it now
}
public class Form2
{
private String _myString = null;
public String MyString { get { return _myString; } }
//same constructor needs...
public Form2(String InputString)
{
_myString = InputString;
}
}
最終,您的呼叫將變爲:
String strToPassAlong = "This is the string";
Form1 f1 = new Form1(strToPassAlong);
f1.MdiParent = this;
f1.Show();
Form2 f2= new Form2(f1.MyString); //or this.MyString, if Form2 is constructed by Form1's code
f2.ShowDialog();
現在,沿途的每個表格都有您傳遞的字符串的副本。