一、窗体间传值的方式;
1、通过通过Tag属性传值;
2、构造函数传值
3、通过事件参数传值
1.1、通过通过Tag属性传值;
//winform窗体间传值(使用Tag属性)
Form1中:
private void Button1_Click(object sender,EventArgs e)
{
Dataset ds=goods.GetInfoDataSet();
if(ds.Table[0].Rows.Count>0)
{
Form2 f2=new Form2();
f2.Tag=ds;
f2.Show();
}
}
Form2中:
private void Form2_Load(object sender,EventArgs)
{
DataSet ds=(DataSet)this.Tag;
if(ds.Table[0].Rows.Count>0)
{
this.textbox1.text=ds.Table[0].Rows[0][0].ToString();
this.textBox2.Text=ds.Table[0].Rows[0][1].ToString();
}
}
1.2、构造函数传值
简单地说就是通过一个按钮的点击事件,在Form2实例化的过程中把From1的控件的值传给From2的构造函数,再把值赋给相应的控件;
Form1中:
//Form1的按钮点击事件内:
private void Button1_Click(object sender,EventArgs e)
{
Form2 f2 = new Form(TextBox.Text);
From2.Show();
}
Form2中:
//From2的构造函数:引入一个String类型的变量
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
//构造函数传值
public Form2(string s)
{
InitializeComponent();
//赋值给From2的Label1,显示出来的文字就是Form1的TextBox.Text;
label1.Text = s;
}
}
1.3、通过事件参数传值
//当前窗体产生一些重要数据,事件作为消息的通知者,将数据存储起来,发送给多个注册此事件的其他窗体
MyEventArg 类
namespace WindowsFormsApp1
{
class MyEventArg : EventArgs
{
public string Text { get; set; }
}
}
Form1中:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public event EventHandler SendMsgEvent; //使用默认的事件处理委托
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
#region 方法3(推荐)--事件方式
//子窗体弹出来之前,注册事件,关注主窗体消息的变化,当有多个窗体需要接收信息,只需要在此修改即可
Form2 f2 = new Form2();
SendMsgEvent += f2.MainFormTxtChaned;//为子窗体注册事件,在子窗体中事件处理代码中设置文本
//触发事件
//EventArgs, 写一个子类继承该类,子类中添加需要封装的数据信息,此处只需要传递string信息,详见MyEventArgs
SendMsgEvent(this, new MyEventArg() { Text = this.textBox1.Text });
f2.ShowDialog();
#endregion
}
}
}
Form2中:
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void MainFormTxtChaned(object sender, EventArgs e)
{
//取到主窗体的传来的数据
MyEventArg arg = e as MyEventArg;
this.textBox1.Text = arg.Text;
}
}
}