Adding an event handler for a control in child form from parent form in C#

前端 未结 1 2000
夕颜
夕颜 2020-11-30 14:13

I have two forms. One is a parent form with a button and a text box. On click of the button, a dialog opens the child form which in turn has a textbox and a button. Now what

相关标签:
1条回答
  • 2020-11-30 14:59

    You can add event in child form and rise it when text changed. Then create event handler in parent form and change text in parent form. In child form:

    public event EventHandler OnChildTextChanged;
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if(OnChildTextChanged != null)
           OnChildTextChanged(textBox1.Text, null);
    }
    

    In parent form:

    private void button1_Click(object sender, EventArgs e)
    {
        ChildForm child = new ChildForm();
        child.OnChildTextChanged += new EventHandler(child_OnChildTextChanged);
        child.ShowDialog();
    }
    
    void child_OnChildTextChanged(object sender, EventArgs e)
    {
        textBox1.Text = (string)sender;
    }
    

    Hope it helps.

    0 讨论(0)
提交回复
热议问题