Set value to another form

后端 未结 4 1698
清歌不尽
清歌不尽 2021-01-21 12:50

I have to form Form1 and Form2

Form1 source

namespace WindowsFormsApplication1
{
    public partial class Form1 :          


        
4条回答
  •  不思量自难忘°
    2021-01-21 13:30

    You need to pass a reference to your Form1 instance to the Form2 instance.

    You can do that like this:

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void label1_Click(object sender, EventArgs e)
            {
                Form2 frm = new Form2(this); // <---- Pass a reference to this form to Form2
                frm.SetBtn = "teste test";
                frm.Show();
            }
    
            public string setLb
            {
                set
                {
                    label1.Text = value;
                }
            }
        }
    }
    

    And you would need to change the Form2 implementation a little aswell:

    namespace WindowsFormsApplication1
    {
        public partial class Form2 : Form
        {
            private Form1 other;
    
            //Empty constructor for the designer
            public Form2()
            {
                InitializeComponent();
            }
    
            public Form2(Form1 other)
            {
                this.other = other;
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                other.setLb = "test test";
            }
    
            public string SetBtn
            {
                set
                {
                    button1.Text = value;
                }
            }
        }
    }
    

提交回复
热议问题