[C#(WinForm)] - 窗体间传值方法

来源:http://hackline.net/a/school/ymbc/C/2009/1221/2343.html

 

// 方法一:所有权法
// ************************************************************************
MainForm (按钮名btnMethod1)

public void myMethod1() { this .Text = " 方法一 " ; }
private void btnMethod1_Click( object sender, EventArgs e)
{
ChildForm child1
= new ChildForm();
child1.Owner
= this ; // 必须设置
child1.ShowDialog();
}

 

 

ChildForm (按钮名btnMethod1)

private void btnMethod1_Click( object sender, EventArgs e)
{
MainForm main1
= (MainForm) this .Owner;
main1.myMethod1();
main1.textBox1.Text
= this .textBox1.Text;
}

 

 

 

 

// 方法二:自身传递法
// ************************************************************************
// MainForm (按钮名btnMethod2)

public void myMethod2() { this .Text = " 方法二 " ; }
private void btnMethod2_Click( object sender, EventArgs e)
{
ChildForm child2
= new ChildForm( this );
child2.ShowDialog(
this );
}

 

 

// ChildForm (按钮名btnMethod2)

private MainForm main2;
public ChildForm(MainForm mainform) // 重载ChildForm
{
InitializeComponent();
main2
= mainform;
}
private void btnMethod2_Click( object sender, EventArgs e)
{
main2.myMethod2();
main2.textBox2.Text
= this .textBox2.Text;
}

 

 

 

 

// 方法三:属性法
// ************************************************************************
// MainForm (按钮名btnMethod3)

public void myMethod3() { this .Text = " 方法三 " ; }
private void btnMethod3_Click( object sender, EventArgs e)
{
ChildForm child3
= new ChildForm();
child3.MAIN3
= this ;
child3.ShowDialog();
}

 

 

// ChildForm (按钮名btnMethod3)

private MainForm main3;
public MainForm MAIN3
{
get { return main3; }
set { main3 = value; }
}
private void btnMethod3_Click( object sender, EventArgs e)
{
main3.myMethod3();
main3.textBox3.Text
= this .textBox3.Text;
}

 

 

 

 

// 方法四:委托法
// ************************************************************************

// MainForm (按钮名btnMethod4)
public delegate void myDelegate4(); // 声明一个委托
public void myMethod4() { this .Text = " 方法四 " ; }
private void btnMethod4_Click( object sender, EventArgs e)
{
ChildForm child4
= new ChildForm();
child4.myDelegate4Test
+= new myDelegate4(myMethod4);
child4.ShowDialog();
}

 

 

// ChildForm (按钮名btnMethod4)

public event MainForm.myDelegate4 myDelegate4Test; // 声明事件
private void btnMethod4_Click( object sender, EventArgs e)
{
myDelegate4Test();
}

 

 

你可能感兴趣的:(WinForm)