服务器之家

服务器之家 > 正文

C#简单实现子窗体向父窗体传值的方法

时间:2021-10-26 13:13     来源/作者:我心依旧

本文实例讲述了C#简单实现子窗体向父窗体传值的方法。分享给大家供大家参考。具体如下:

击Form1的button1 打开Form2
再点击Form2的button2

在button2_Click事件中 通过this.Owner将Form2的textBox2的值设置给Form1的textBox1
并关闭Form2

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public partial class Form1 : Form
{
  public Form1()
  {
   InitializeComponent();
  }
  private void button1_Click(object sender, EventArgs e)
  {
   Form2 frm2 = new Form2();
   frm2.Show(this);//或 frm2.ShowDialog(this);
   ////或者
   //Form2 frm2 = new Form2();
   //frm2.Owner = this;
   //frm2.Show();//或 frm2.ShowDialog();
  }
}
public partial class Form2 : Form
{
  public Form2()
  {
   InitializeComponent();
  }
  private void button2_Click(object sender, EventArgs e)
  {
   Form1 frm1 = (Form1)this.Owner;
  //注意 如果textBox1是放在panel1中的 则先找panel1 再找textBox1
   ((TextBox)frm1.Controls["textBox1"]).Text = this.textBox2.Text;
   this.Close();
  }
}

点击Form1的button1 打开Form2
再点击Form2的button2
在button2_Click事件中 通过this.Owner及调用父窗体Form1的公开属性或方法

将Form2的textBox2的值设置给Form1的textBox1
并关闭Form2

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public partial class Form1 : Form
{
  public Form1()
  {
   InitializeComponent();
  }
  public string TextBox1Text
  {
   set { this.textBox1.Text = value; }
   get { return this.textBox1.Text; }
  }
  private void button1_Click(object sender, EventArgs e)
  {
   Form2 frm2 = new Form2();
   frm2.Show(this);//或 frm2.ShowDialog(this);
   ////或者
   //Form2 frm2 = new Form2();
   //frm2.Owner = this;
   //frm2.Show();//或 frm2.ShowDialog();
  }
}
public partial class Form2 : Form
{
  public Form2()
  {
   InitializeComponent();
  }
  private void button2_Click(object sender, EventArgs e)
  {
   Form1 frm1 = (Form1)this.Owner;
   frm1.TextBox1Text = this.textBox2.Text;
   this.Close();
  }
}

希望本文所述对大家的C#程序设计有所帮助。

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部