C#窗体间传值,非父窗体与子窗体
时间: 2024-12-07 18:12:41 浏览: 17
在C#中,窗体间传值是一个常见的需求,尤其在非父子关系的窗体之间传值。下面介绍几种常用的方法:
### 1. 使用公共变量
可以在一个公共类中定义静态变量,然后在不同的窗体中访问这些变量。
```csharp
// 公共类
public static class CommonData
{
public static string Data { get; set; }
}
// 窗体1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CommonData.Data = "Hello from Form1";
Form2 form2 = new Form2();
form2.Show();
}
}
// 窗体2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = CommonData.Data;
}
}
```
### 2. 使用构造函数
在创建子窗体时,通过构造函数传递数据。
```csharp
// 窗体1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string data = "Hello from Form1";
Form2 form2 = new Form2(data);
form2.Show();
}
}
// 窗体2
public partial class Form2 : Form
{
private string receivedData;
public Form2(string data)
{
InitializeComponent();
receivedData = data;
}
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = receivedData;
}
}
```
### 3. 使用事件
通过事件机制传递数据。
```csharp
// 公共事件参数类
public class DataEventArgs : EventArgs
{
public string Data { get; set; }
}
// 窗体1
public partial class Form1 : Form
{
public event EventHandler<DataEventArgs> DataSent;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataEventArgs args = new DataEventArgs { Data = "Hello from Form1" };
DataSent?.Invoke(this, args);
}
}
// 窗体2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.DataSent += Form1_DataSent;
form1.Show();
}
private void Form1_DataSent(object sender, DataEventArgs e)
{
label1.Text = e.Data;
}
}
```
### 4. 使用委托
通过委托传递数据。
```csharp
// 窗体1
public partial class Form1 : Form
{
public delegate void SendDataDelegate(string data);
public event SendDataDelegate SendData;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SendData?.Invoke("Hello from Form1");
}
}
// 窗体2
public partial class Form2 : Form
{
private string receivedData;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.SendData += Form1_SendData;
form1.Show();
}
private void Form1_SendData(string data)
{
label1.Text = data;
}
}
```
阅读全文