Propagating events from one Form to another Form in C#

后端 未结 3 2061
心在旅途
心在旅途 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:35

    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.

    0 讨论(0)
  • 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...";
        }
    }
    
    0 讨论(0)
  • 2020-12-06 03:55

    Assuming WinForms;

    If the textbox is bound to a property of an object, you would implement the INotifyPropertyChanged interface on the object, and notify about the value of the string being changed.

    public class MyClass : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        private string title;
        public string Title {
          get { return title; } 
          set { 
            if(value != title)
            {
              this.title = value;
              if (this.PropertyChanged != null)
              {
                 this.PropertyChanged(this, new PropertyChangedEventArgs("Title"));
              }
           }
      }
    

    With the above, if you bind to the Title property - the update will go through 'automatically' to all forms/textboxes that bind to the object. I would recommend this above sending specific events, as this is the common way of notifying binding of updates to object properties.

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