主窗体与子窗体传值:

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

C#窗体传值-示例

图2

C#窗体传值-示例

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

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

 

相关文章:

  • 2022-03-04
  • 2021-09-25
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
  • 2021-10-19
  • 2022-01-08
猜你喜欢
  • 2021-11-28
  • 2021-10-20
  • 2021-12-11
  • 2021-11-05
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
相关资源
相似解决方案