寫WinForm的程式,使用Form與Form之間的傳值方式並不少見,但從WebForm跳來寫WinForm的,可能就會搞不清楚WinForm的做法,所以這個問題也被常常拿出來,所以這邊大概列了幾種做法供參考.
1. 在Form1輸入值,在開啟Form2時,顯示Form2的值,而Form2關閉後,將Form2的值帶回Form1.
Form2
public Form2()
{
InitializeComponent();
}
public Form2(string strTextMsg)
{
InitializeComponent();
textBox1.Text = strTextMsg;
}
public string TextBoxMsg
{
set
{
textBox1.Text = value;
}
get
{
return textBox1.Text;
}
}
Form1
方式1
Form2 obj = new Form2();
obj.TextBoxMsg = textBox1.Text;//把form1的值設定到form2
if (obj.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = obj.TextBoxMsg;//從form2取值設定到form1
}
方式2
Form2 obj = new Form2(textBox1.Text);//把Form1的值給到Form2
if (obj.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = obj.TextBoxMsg;從Form2取值並顯示到Form1
}
2. 在Form2沒有關閉的情況下,Form2對Form1傳值與執行Form1的Function
Form2
public Form2(Form1 Parentform)//Parent Form
{
InitializeComponent();
this.Tag = Parentform;
}
private void button1_Click(object sender, EventArgs e)
{
((Form1)this.Tag).setTextBoxMsg = textBox1.Text;//傳值設定Form1的TextBox
((Form1)this.Tag).DoSomething("From Child");//執行Form1的Function
}
Form1
private void button4_Click(object sender, EventArgs e)
{
Form2 obj = new Form2(this);
obj.ShowDialog();
}
public string setTextBoxMsg
{
set
{
textBox1.Text = value;
}
}
public void DoSomething(string Msg)
{
MessageBox.Show(Msg);
}
3. 同樣是Form1取Form2的值,不過做法是直接將Control的Modifiers可見層級提升.
Form2
以這個例子來說,Modifiers設為Internal.
internal System.Windows.Forms.TextBox textBox1;
Form1
Form2 obj = new Form2();
obj.ShowDialog();
textBox1.Text = obj.textBox1.Text;//這裡就可以直接拿Form2來用,所以Text屬性當然也能取得.
4. MDI的各Form互相傳值.
MDI Form Container1
Form2 f 2 = new Form2();
f2.MdiParent = this;
f2.Show();
Form3 f 3 = new Form3();
f3.MdiParent = this;
f3.Show();
MDI Clild Form Form2 傳值給同樣是MDI Child Form的Form3
Form2
Form[] aryf = this.Parent.FindForm().MdiChildren;
foreach (Form f in aryf)
{
if (f.Name == "Form3")
{
((Form3)f).TextBoxMsg =
textBox1.Text; ;
break;
}
}
Form3
public string TextBoxMsg
{
set
{
textBox1.Text = value;
}
get
{
return textBox1.Text;
}
}
MDI Form2設定Parent Container的Text1
this.Parent.FindForm().Text = textBox1.Text;
沒有留言:
張貼留言