Propagating events from one Form to another Form in C#

后端 未结 3 2060
心在旅途
心在旅途 2020-12-06 03:14

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

3条回答
  •  有刺的猬
    2020-12-06 03:55

    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...";
        }
    }
    

提交回复
热议问题