现假设有2个窗体;
从form1启动form2;
需要在form1中,初始化设置form2窗体上的各个控件;使其显示初始值;
此时最好的方法是用form2的公共字段;代码看上去比较清晰;
form2代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace chzhdemo1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
public string txt1
{
set { textBox1.Text = value; }
get { return textBox1.Text; }
}
public string combo1
{
set { comboBox1.Text = value; }
get { return comboBox1.Text; }
}
public decimal num1
{
set { numericUpDown1.Value = value; }
get { return numericUpDown1.Value; }
}
public bool rdchk1
{
set { radioButton1.Checked = value; }
get { return radioButton1.Checked; }
}
public string txt2
{
set { textBox2.Text = value; }
get { return textBox2.Text; }
}
public string txt3
{
set { textBox3.Text = value; }
get { return textBox3.Text; }
}
}
}
对要传值的控件,的属性值,定义公共字段,写好它的get、set方法;
form1代码;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace chzhdemo1
{
public partial class Form1 : Form
{
Form2 f2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
f2 = new Form2();
f2.txt1 = "黄飞鸿";
f2.combo1 = "广州市";
f2.num1 = 33;
f2.rdchk1 = true;
f2.txt2 = "宝芝林有限公司";
f2.txt3 = "无影拳";
f2.ShowDialog();
}
}
}
定义了公共字段以后在form1可以访问form2中的公共字段;进行赋值;
form2的2个文本框,定义string类型的公共字段;数值框,定义decimal类型的公共字段;为combobox的text属性赋值,也定义string类型的公共字段;要从form1设置form2的radiobutton选中与否,其checked属性是bool类型,定义bool类型公共字段;
上述代码效果如下: