Form1
using System;
using System.Windows.Forms;
namespace PassDataFromChildToParent
{
public partial class FrmParent : Form
{
public string ParentText
{
get { return this.textBox1.Text; }
set { this.textBox1.Text = value; }
}
public FrmParent()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FrmChild frm = new FrmChild(this);
frm.ShowDialog();
//1.直接访问控件值
//this.textBox2.Text = (frm.Controls["monthCalendar1"] as MonthCalendar).SelectionStart.ToShortDateString();
//2.访问属性值
this.textBox2.Text = frm.ChileDate.ToShortDateString();
}
}
}
Form2:
using System;
using System.Windows.Forms;
namespace PassDataFromChildToParent
{
public partial class FrmChild : Form
{
private FrmParent _ParentForm;
public DateTime ChileDate
{
get { return this.monthCalendar1.SelectionStart; }
set { this.monthCalendar1.SelectionStart = value; }
}
public FrmChild(FrmParent parent)
{
InitializeComponent();
_ParentForm = parent;
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
//1.设置控件值
//(_ParentForm.Controls["textBox1"] as TextBox).Text = monthCalendar1.SelectionStart.ToShortDateString();
//2.设置属性值
_ParentForm.ParentText = monthCalendar1.SelectionStart.ToShortDateString();
}
}
}
把一个窗体中的值传给另一个窗体的文本框控件:
1)在当前窗体Form1传递,可直接将该值通过以下语句传递:
Form2.Text1.Text = 136
2)也可通过模块级全局变量传递。
这种分两种情况:1、form2在form1前面可以利用窗体传值就可以实现,在form1中增加一个带有参数的构造函数;2、form1在form2前面,可以修改form1的textbox1的访问属性为public,使textbox1在form2中能访问,实现日期值=textbox1.text;
Form1
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
using System;
using System.Windows.Forms;
namespace PassDataFromChildToParent
{
public partial class FrmParent : Form
{
public string ParentText
{
get { return this.textBox1.Text; }
set { this.textBox1.Text = value; }
}
public FrmParent()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FrmChild frm = new FrmChild(this);
frm.ShowDialog();
//1.直接访问控件值
//this.textBox2.Text = (frm.Controls["monthCalendar1"] as MonthCalendar).SelectionStart.ToShortDateString();
//2.访问属性值
this.textBox2.Text = frm.ChileDate.ToShortDateString();
}
}
}
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
using System;
using System.Windows.Forms;
namespace PassDataFromChildToParent
{
public partial class FrmChild : Form
{
private FrmParent _ParentForm;
public DateTime ChileDate
{
get { return this.monthCalendar1.SelectionStart; }
set { this.monthCalendar1.SelectionStart = value; }
}
public FrmChild(FrmParent parent)
{
InitializeComponent();
_ParentForm = parent;
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
//1.设置控件值
//(_ParentForm.Controls["textBox1"] as TextBox).Text = monthCalendar1.SelectionStart.ToShortDateString();
//2.设置属性值
_ParentForm.ParentText = monthCalendar1.SelectionStart.ToShortDateString();
}
}
}