C#.有两个窗体,分别为窗体 1 和窗体 2。在窗体 1 中单击打开窗体 2, 打开窗体 2,并把窗体 1 中文本框的值赋给窗体 2 中的文本框中。 在窗体 2 中单击关闭窗体 2,把窗体 2 中的文本框的值赋给窗体 1 的文本框中,然后关闭窗体 2.要求用委托实现运行成功截图
时间: 2024-05-01 08:21:06 浏览: 16
以下是示例代码实现:
在窗体1中添加一个按钮和一个文本框:
```C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(); // 创建窗体2的实例
form2.SetText(textBox1.Text); // 调用窗体2的方法,将窗体1的文本框的值传递过去
form2.ShowDialog(); // 显示窗体2
textBox1.Text = form2.GetText(); // 获取窗体2文本框的值,并赋值给窗体1的文本框
}
}
```
在窗体2中添加一个文本框和一个按钮:
```C#
public partial class Form2 : Form
{
public delegate void SetTextDelegate(string text); // 委托类型,用于传递窗体1的文本框的值
public delegate string GetTextDelegate(); // 委托类型,用于传递窗体2文本框的值
private SetTextDelegate setTextDelegate; // 声明委托变量,用于传递窗体1的文本框的值
private GetTextDelegate getTextDelegate; // 声明委托变量,用于传递窗体2文本框的值
public Form2()
{
InitializeComponent();
}
public void SetText(string text)
{
setTextDelegate = new SetTextDelegate(SetTextMethod); // 创建委托实例
this.Invoke(setTextDelegate, text); // 调用委托方法,将窗体1的文本框的值传递过来
}
public string GetText()
{
getTextDelegate = new GetTextDelegate(GetTextMethod); // 创建委托实例
return (string)this.Invoke(getTextDelegate); // 调用委托方法,获取窗体2文本框的值并返回
}
private void button1_Click(object sender, EventArgs e)
{
this.Close(); // 关闭窗体2
}
private void SetTextMethod(string text)
{
textBox1.Text = text; // 将窗体1的文本框的值赋值给窗体2的文本框
}
private string GetTextMethod()
{
return textBox1.Text; // 获取窗体2的文本框的值并返回
}
}
```
运行程序后,单击窗体1中的按钮,会弹出窗体2,窗体2的文本框中会显示窗体1中的文本框的值。在窗体2中单击关闭按钮,会将窗体2的文本框的值赋值给窗体1的文本框中,并关闭窗体2。最终效果如下图所示:
![C#委托实现窗体间文本框值传递](https://img-blog.csdn.net/20180321231017792?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmFpZHVhYnNlbnRlcnJhZGlvbg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/85)
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)