標籤:
windows form (表單) 之間傳值小結
在windows form之間傳值,我總結了有四個方法:全域變數、屬性、表單建構函式和delegate。第一個全域變數:這個最簡單,只要把變數描述成static就可以了,在form2中直接引用form1的變數,代碼如下:在form1中定義一個static變數public static int i= 9 ;Form2中的鈕扣按鈕如下:private void button1_Click(object sender, System.EventArgs e){ textBox1.Text = Form1.i.ToString();} 第二個方法是利用屬性,請詳部落格:http://blog.csdn.net/tjvictor/archive/2006/06/04/772711.aspx 第三個方法是用建構函式:Form1 的button按鈕這樣寫:private void button1_Click(object sender, System.EventArgs e){ Form2 temp = new Form2( 9 ); temp.Show();} Form2 的建構函式這樣寫:public Form2( int i ){ InitializeComponent(); textBox1.Text = i.ToString();} 第四個方法是用delegate,代碼如下:Form2中先定義一個delegatepublic delegate void returnvalue( int i );public returnvalue ReturnValue;form2 中的button按鈕代碼如下:private void button1_Click(object sender, System.EventArgs e){ if ( ReturnValue != null ) ReturnValue( 8 );} Form1中的button按鍵如下:private void button1_Click(object sender, System.EventArgs e){ Form2 temp = new Form2( ); temp.ReturnValue = new temp.Form2.returnvalue( showvalue ); temp.Show();} private void showvalue( int i ){ textBox1.Text = i.ToString();} 點擊form2的button,form1中的textbox中的值就會相應變化。 在這四個方法中,第一個是雙向傳值,也就是說,form1和form2改變i的值,另一方也會受到影響。第二個方法可以單向也可以雙向傳值。第三個方法是form1->form2單向傳值。第四個方法是form2->form1單向傳值。 以後有新的方法我再補充,還有一個就是用event,和delegate差不多,在這裡就不說了windows form (表單) 之間傳值小結在windows form之間傳值,我總結了有四個方法:全域變數、屬性、表單建構函式和delegate。第一個全域變數:這個最簡單,只要把變數描述成static就可以了,在form2中直接引用form1的變數,代碼如下:在form1中定義一個static變數public static int i= 9 ;Form2中的鈕扣按鈕如下:private void button1_Click(object sender, System.EventArgs e){ textBox1.Text = Form1.i.ToString();} 第二個方法是利用屬性,請詳見部落格:http://blog.csdn.net/tjvictor/archive/2006/06/04/772711.aspx 第三個方法是用建構函式:Form1 的button按鈕這樣寫:private void button1_Click(object sender, System.EventArgs e){ Form2 temp = new Form2( 9 ); temp.Show();} Form2 的建構函式這樣寫:public Form2( int i ){ InitializeComponent(); textBox1.Text = i.ToString();} 第四個方法是用delegate,代碼如下:Form2中先定義一個delegatepublic delegate void returnvalue( int i );public returnvalue ReturnValue;form2 中的button按鈕代碼如下:private void button1_Click(object sender, System.EventArgs e){ if ( ReturnValue != null ) ReturnValue( 8 );} Form1中的button按鍵如下:private void button1_Click(object sender, System.EventArgs e){ Form2 temp = new Form2( ); temp.ReturnValue = new temp.Form2.returnvalue( showvalue ); temp.Show();} private void showvalue( int i ){ textBox1.Text = i.ToString();} 點擊form2的button,form1中的textbox中的值就會相應變化。 在這四個方法中,第一個是雙向傳值,也就是說,form1和form2改變i的值,另一方也會受到影響。第二個方法可以單向也可以雙向傳值。第三個方法是form1->form2單向傳值。第四個方法是form2->form1單向傳值。
windows form (表單) 之間傳值小結