方法一:委托(事件)方法
(1)父窗体Form1代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//父窗体中的2个待传(传至子窗)字段
public List<string> data1 = new List<string>() { "111", "222" };
public List<string> data2 = new List<string>() { "333", "444" };
//按照委托定义的方法
private List<string> TransData1()
{
return this.data1;
}
private List<string> TransData2()
{
return this.data2;
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
//给子窗体的事件绑定实现方法
//frm2.SendTo += TransData1; //直接绑定
frm2.SendTo += delegate() { return data2; }; //匿名方法
frm2.SendTo += () => data2; //lanmuda表达式(无参、有多参都要括号)
frm2.Show(this); //非模态对话框
}
}
(2)子窗体Form2代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public delegate List<string> SomeDelegate(); //委托类型(无参、List<>类型)
public event SomeDelegate SendTo; //事件封装委托
private void button1_Click(object sender, EventArgs e)
{
List<string> point=new List<string>();
point.AddRange(SendTo());
if (this.SendTo != null)
{
foreach (var i in point)
{
MessageBox.Show(i);
}
}
}
}
方法二:公有属性/方法
(1)父窗体Form1代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public List<double> text = new List<double>() { 11, 22, 33, 44, 55, 66 };//字段
public List<double> TextTanspose //公有属性封装字段
{
get { return this.text; }
set { this.text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.Show(this); //非模态对话框
//frm2.ShowDialog(this); 模态对话框
}
}
(2)子窗体Form2代码:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = (Form1)this.Owner;
List<double> data = frm1.TextTanspose; //使用属性get
foreach(var ii in data )
{
MessageBox.Show(ii.ToString());
}
}
}
希望以上讨论能对新学习的朋友有所帮助!