WinForm窗體間傳值

2021-09-06 22:31:50 字數 2400 閱讀 9386

1.通過建構函式

特點:傳值是單向的(不可以互相傳值),實現簡單

實現**如下:

在窗體form2中      

int value1;

string value2;

public form2 ( int value1 , string value2 )

initializecomponent ( );

this.value1 = value1;

this.value2 = value2;

在窗體form1中這樣呼叫

new form2 ( 111 , "222" ).show ( );  //這樣就把111,"222",這2個值傳送給了form2

2.通過靜態變數

特點:傳值是雙向的,實現簡單

實現**如下:

public static string value;

在窗體form1中這樣呼叫

new form2 ( ).show ( );  //顯示form2

在窗體form2中     

3.通過窗體的公有屬性值

特點:實現簡單

實現**如下:

在窗體form2中定義乙個公有屬性form2value,獲取和設定textbox1的文字值

public string form2value

getreturn this.textbox1.text;

setthis.textbox1.text = value;

在窗體form1中這樣呼叫

form2 f2 = new form2 ( );

f2.form2value = "ok";     //給form2的textbox1賦值ok

f2.showdialog (  );

4.通過窗體的公有屬性值和owner屬性

特點:實現簡單,靈活

實現**如下:

在窗體form1中

public int form1value = 1;

form2 f2 = new form2 ( );

f2.showdialog ( this );       //把form1作為form2的所有者傳遞給form2

在窗體form2中

//form2的所有者是form1

form1 f1 = ( form1 ) this.owner;

//取到form1的值是1

messagebox.show ( f1.form1value .tostring ( ) );

//給form1的form1value賦值222

f1.form1value = 222;

實現**如下:

在窗體form1中

public int form1value = 1;

form2 f2 = new form2 ( );

f2.show ( );

在窗體form2中

string formname = "form1";

if ( fr != null )

form1 f1 = ( form1 ) fr;

//取到form1的值是1

messagebox.show ( f1.form1value.tostring ( ) );

//給form1的form1value賦值222

f1.form1value = 222;

6.通過事件

實現**如下:

在窗體form2中定義公有屬性form2value,獲取和設定textbox1的文字值

並且還定義乙個accept事件

public string form2value

getreturn this.textbox1.text;

setthis.textbox1.text = value;

public event eventhandler accept;

private void button1_click ( object sender , eventargs e )

if ( accept != null )

accept ( this , eventargs.empty );  //當窗體觸發事件,傳遞自身引用

在窗體form1中

form2 f2 = new form2 ( );

f2.accept += new eventhandler ( f2_accept );

f2.show ( );

void f2_accept ( object sender , eventargs e )

//事件的接收者通過乙個簡單的型別轉換得到form2的引用

form2 f2 = (form2) sender;

//接收到form2的textbox1.text

this.textbox1.text = f2.form2value;

WinForm窗體間傳值

form1 主窗體 namespace firstdlg public string textstored set private void button1 click object sender,eventargs e private void form1 load object sender,e...

winform窗體間傳值

推薦使用第6與第7方法 1.通過建構函式 特點 傳值是單向的 不可以互相傳值 實現簡單 實現 如下 在窗體form2中 int value1 string value2 public form2 int value1 string value2 在窗體form1中這樣呼叫 new form2 111...

winform窗體間傳值

1.通過建構函式 特點 傳值是單向的 不可以互相傳值 實現簡單 實現 如下 在窗體form2中 int value1 string value2 public form2 int value1 string value2 在窗體form1中這樣呼叫 new form2 111 222 show 這樣...