Best way to communicate between forms?

后端 未结 4 1722
礼貌的吻别
礼貌的吻别 2020-12-21 08:51

I almost never used (advanced, or at all) graphical interfaces, or one simple form with simple controls... but this time I\'ve got something a little more complex, and I don

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-21 09:10

    Your constructor idea is probably the most sound method of communication back to the main form. Your sub form would do something like the following:

    public class SubForm : Form
    {
        public SubForm(MainForm parentForm)
        {
            _parentForm = parentForm;
        }
    
        private MainForm _parentForm;
    
        private void btn_UpdateClientName_Click(object sender, EventArgs e)
        {
            _parentForm.UpdateClientName(txt_ClientName.Text);
        }
    }
    

    And then you expose public methods on your MainForm:

    public class MainForm : Form
    {
        public void UpdateClientName(string clientName)
        {
            txt_MainClientName.Text = clientName;
        }
    }
    

    Alternatively, you can go the other way around and subscribe to events from your SubForms:

    public class MainForm : Form
    {
        private SubForm1 _subForm1;
        private SubForm2 _subForm2;
    
        public MainForm()
        {
            _subForm1 = new SubForm1();
            _subForm2 = new SubForm2();
    
            _subForm1.ClientUpdated += new EventHandler(_subForm1_ClientUpdated);
            _subForm2.ClientUpdated += new EventHandler(_subForm2_ProductUpdated);
        }
    
        private void _subForm1_ClientUpdated(object sender, EventArgs e)  
        {
            txt_ClientName.Text = _subForm1.ClientName; // Expose a public property
        }
    
        private void _subForm2_ProductUpdated(object sender, EventArgs e)  
        {
            txt_ProductName.Text = _subForm2.ProductName; // Expose a public property
        }
    }
    

提交回复
热议问题