第一種利用委託的方法:
父表單的方法:
private void constraintEnd_Click(object sender, EventArgs e) { //if (MessageBox.Show("即將強制將本爐次資料歸檔!", "警告", MessageBoxButtons.OKCancel) == DialogResult.OK)//2012.4.11修改 //{ CCMEnd ccmend = new CCMEnd(curHeatInfo.Rows[0]["heatid"].ToString(), label337.Text.ToString().Trim()); ccmend.resultEvent += new CCMEnd.CalculateDelegate(Endccm); ccmend.Show(this); } public void Endccm(string result) { checkProcStatus(); if (result.Equals("1")) { //MessageBox.Show("歸檔成功!", "警告");//2012.4.11修改 MessageBoxTimeout.Show("歸檔成功!", "警告", 4000); } else { //MessageBox.Show(result, "警告"); MessageBoxTimeout.Show(result, "警告", 4000); } //} }
子表單方法:
public delegate void CalculateDelegate(string result); public event CalculateDelegate resultEvent; private void button1_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox4.Text) && !string.IsNullOrEmpty(textBox5.Text)) { QT_Service.QT_Service qtService = new UI.QT_Service.QT_Service(); int cut_head = Int16.Parse(textBox4.Text); int cut_trimmed = Int16.Parse(textBox5.Text); result = qtService.EndEAFHeatID(4, string.Format("{0:yyyyMMddHHmmss}", DateTime.Now), cut_head, cut_trimmed); //CalculateDelegate calculate = new CalculateDelegate(((CCMMonitor)this.Owner).Endccm); //calculate(result); this.Close(); resultEvent(result); } else { MessageBox.Show("輸入有誤,請重新輸入!", "警告"); } }
第二種方法:
父視窗:
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 frm = new Form2(this,textBox1.Text);//帶參數構造Form2(此方法該處帶倆參數構造多餘) if (frm.ShowDialog() == DialogResult.OK) { this.textBox1.Text += frm.ReturnText;//通過Form2的屬性獲得回傳值 } frm = null; }
子視窗:
public partial class Form2 : Form { private Form1 pfrm; private string frm1txt; public Form2(Form1 parentfrm,string frm1text) { InitializeComponent(); pfrm = parentfrm; frm1txt = frm1text; } public string ReturnText//回傳值的屬性 { get { return this.frm1txt; } } private void button2_Click(object sender, EventArgs e)//給屬性賦值並關閉模式表單Form2 { frm1txt = this.textBox2.Text; this.DialogResult = DialogResult.OK;//*必加 模式表單開啟後 只有DialogResult初始化後才可繼續操作 否則值無法傳回 this.Close();//模式表單關閉.close()相當於將表單隱藏 徹底關閉需要用.Dispose() } private void button3_Click(object sender, EventArgs e)//關閉 { this.DialogResult = DialogResult.Cancel;//同* this.Close(); }
第三種方法就是將父視窗的對象當做參數傳到子視窗。
參考:http://www.cnblogs.com/wangchunming/archive/2011/12/10/2282962.html