Communicate between two windows forms in C#

后端 未结 12 1815
温柔的废话
温柔的废话 2020-11-21 04:40

I have two forms, one is the main form and the other is an options form. So say for example that the user clicks on my menu on the main form: Tools -> Options

12条回答
  •  鱼传尺愫
    2020-11-21 05:35

    Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.

    With this approach you can do communication in different ways.

    Download Link for Sample Project

    //Your Form1

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm = new Form2(this);
            frm.Show();
        }
    
        public string LabelText
        {
            get { return Lbl.Text; }
            set { Lbl.Text = value; }
        }
    }
    

    //Your Form2

    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
    
        private Form1 mainForm = null;
        public Form2(Form callingForm)
        {
            mainForm = callingForm as Form1; 
            InitializeComponent();
        }
    
        private void Form2_Load(object sender, EventArgs e)
        {
    
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            this.mainForm.LabelText = txtMessage.Text;
        }
    }
    


    (source: ruchitsurati.net)


    (source: ruchitsurati.net)

提交回复
热议问题