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

11,138

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.

Share:
11,138
swordfish
Author by

swordfish

Open Source Enthusiast and Start Up Evangelist working for a corporate, with a start up culture, and an Agile Preacher.

Updated on June 11, 2022

Comments

  • swordfish
    swordfish almost 2 years

    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 I want is whenever the text in the child form textbox changes the text in the parent form textbox changes automatically. To acquire this, what I did is:

    Form3 f3 = new Form3();
    f3.delBetInpTxt.TextChanged +=new EventHandler(delBetInpTxt_TextChanged);
    public void delBetInpTxt_TextChanged(object sender, EventArgs e)
        {
            TextBox t = (TextBox)sender;
            simDelTxt.Text = t.Text + " ms";
        }
    

    I added the above code in the parent form and the child form is Form3. But nothing happens, the parent form textbox still doesn't change even after changing the text in the child form. What am I doing wrong here?

  • Josh Davis
    Josh Davis over 8 years
    by swapping the implementation I was able to click a menu button on my parentform and enable a button on my usercontrol. So thanks for the answer
  • Huzaifa
    Huzaifa over 3 years
    This is giving me error. 'Form' does not contain a definition for 'OnFilterQueryGenerated' and no extension method 'OnFilterQueryGenerated' accepting a first argument of type 'Form' could be found (are you missing a using directive or an assembly reference?). I followed exactly what you did.
  • Renatas M.
    Renatas M. over 3 years
    @Huzaifa99 In my example there is no Form class user and there is no method named OnFilterQueryGenerated. To help you, you need to show your code.