winform 父窗体与子窗体数据传递

本文介绍了如何在C#的WindowsForms应用程序中使用事件委托实现父子窗体之间的数据传递,包括通过控件和函数两种方式,并提供了相应的代码实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实例截图

父窗体代码如下:


public partial class Form1 : Form
{
Child2 child2 = new Child2();
public Form1()
{
InitializeComponent();
child2.receive += new Child2.receiveData(testReceive);
}

private void button2_Click(object sender, EventArgs e)
{
string ls = textBox1.Text;
for(int i=0;i< child2.Controls.Count; i++)
{
Control c = child2.Controls[i];
if (c.Name == "txtReceive")
{
c.Text = "通过查找控件传递数据:"+ls;
}
}

child2.getReceiveData("通过函数传递数据:"+ls);

}

private void button3_Click(object sender, EventArgs e)
{
child2.Show();
}

private void testReceive(object o)
{
textBox2.Text = o.ToString();
}
}

子窗体代码如下:

public partial class Child2 : Form
{
public delegate void receiveData(object o);
public event receiveData receive;
public Child2()
{
InitializeComponent();
}

public void getReceiveData(object o)
{
txtReceive2.Text = o.ToString();
}
public void Receive(object o)
{
receive(o);
}

private void button1_Click(object sender, EventArgs e)
{
Receive(txtReceive3.Text);
}
}

一个简单的父子窗体数据传递。亲测,可以实现上面的效果,谢谢!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值