Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Propagating events from one Form to another Form in C#

How can I click a Button in one form and update text in a TextBox in another form?

like image 601
user366312 Avatar asked Jun 10 '09 18:06

user366312


People also ask

How to handle events in C#?

Event handlers in C#An event handler in C# is a delegate with a special signature, given below. The first parameter (sender) in the above declaration specifies the object that fired the event. The second parameter (e) of the above declaration holds data that can be used in the event handler.


2 Answers

If you're attempting to use WinForms, you can implement a custom event in your "child" form. You could have that event fire when the button in your "child" form was clicked.

Your "parent" form would then listen for the event and handle it's own TextBox update.

public class ChildForm : Form
{
    public delegate SomeEventHandler(object sender, EventArgs e);
    public event SomeEventHandler SomeEvent;

    // Your code here
}

public class ParentForm : Form
{
    ChildForm child = new ChildForm();
    child.SomeEvent += new EventHandler(this.HandleSomeEvent);

    public void HandleSomeEvent(object sender, EventArgs e)
    {
        this.someTextBox.Text = "Whatever Text You Want...";
    }
}
like image 109
Justin Niessner Avatar answered Nov 14 '22 21:11

Justin Niessner


Roughly; the one form must have a reference to some underlying object holding the text; this object should fire an event on the update of the text; the TextBox in another form should have a delegate subscribing to that event, which will discover that the underlying text has changed; once the TextBox delegate has been informed, the TextBox should query the underlying object for the new value of the text, and update the TextBox with the new text.

like image 24
Paul Sonier Avatar answered Nov 14 '22 21:11

Paul Sonier