C#窗体传值-示例

主窗体与子窗体传值:

Form1代码

public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();
            form2.String1=textBoxClass.Text;
            form2.SetValue();

            form2.ChangeText += (str) => textBoxName.Text = str; //用lambda表达式
            form2.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

Form2代码

public partial class Form2 : Form
    {
        //定义一个属性,字段,存储主窗体传过来的string数据
        private string str1;
        public string String1
        {
            set{
                 str1=value;
                }
        }
        public void SetValue()
        {
            this.textBox2.Text = str1;  // textBox2的Text属性赋值            
        }

        public Form2()
        {
           InitializeComponent();
        }
       
        public Action<string> ChangeText; //定义委托事件 传回至主窗体值

        private void button1_Click(object sender, EventArgs e)
        {
            if (ChangeText != null)
            {
                ChangeText(textBoxName.Text.Trim()); //执行事件
                this.Close();
            }

        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            //ChangeText(textBox2.Text.Trim()); //执行事件  
        }

    }

运行效果:图1

图2

=================== 华丽的分割线 ============================================

通过自窗体类的属性传值,主窗体通过事件更新子窗体传过来的值!!!

 

posted @ 2019-05-24 23:52  ChinaHunter  阅读(336)  评论(0编辑  收藏  举报