c#父子窗体的传值

1,父窗体传值到子窗体:通过子窗体的构造函数;

FORM1:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Form2 frm;

        private void Form1_Load(object sender, EventArgs e)
        {
              frm = new Form2();
              //frm.receive += new EventHandler(f2_accept); 

              //
              frm.receive += new EventHandler(
                  (sender1, e1) =>
                  {
                      textBox1.Text = frm.Form2Value;
                  }
                  );

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Form2 frm = new Form2(textBox1.Text);
            //if (frm.ShowDialog() == DialogResult.OK)
            //{
            //    textBox1.Text = frm.TextBoxValue;
            //    frm.Close();
            //}

            
            frm.Show ( );

        }

        void f2_accept(object sender, EventArgs e)
        {
            //事件的接收者通过一个简单的类型转换得到Form2的引用
            //Form2 f2 = sender as Form2;
            if (frm != null)
            //接收到Form2的textBox1.Text
                this.textBox1.Text = frm.Form2Value;
        }
    }

FORM2:

public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        public Form2(string value)
        {
            InitializeComponent();
            TextBoxValue = value;
        }

        private string textBoxvalue;
        public string TextBoxValue
        {
            //get { return textBox1.Text; }
            //set { textBox1.Text = value; }
            get { return textBoxvalue; }
            set { textBoxvalue = value; }
            //get;
            //set;
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //this.DialogResult = DialogResult.OK;
            //textBoxvalue = textBox1.Text;
            //if ( accept != null )
            //{
            //    accept (this , EventArgs.Empty ); //当窗体触发事件,传递自身引用
            //}

            if (receive != null)
            {
                receive(this, EventArgs.Empty);
            }
        }

        public string Form2Value
        {
            get
            {
                return this.textBox1.Text;
            }
            set
            {
                this.textBox1.Text = value;
            }
        }

        public event EventHandler accept;
        public event EventHandler receive;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            receive(this, EventArgs.Empty);
        }
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值