Spreading events from one form to another. Form in C #

How can I click a button in one form and update text in a text box in another form?

+6
c # event-handling events
source share
3 answers

If you are trying to use WinForms, you can implement the custom event in your "child" form. You may have this event when a button is clicked in your "child" form.

Your "parent" form then listens for the event and processes its 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..."; } } 
+14
source share

Rough; one form should have a link to some basic object containing text; this object should trigger an event when updating text; A TextBox in another form must have a delegate who signs up for this event, who discovers that the main text has been changed; as soon as the TextBox delegate is informed, the TextBox should request the base object for the new text value and update the TextBox with the new text.

+1
source share

Assuming WinForms;

If the text field is bound to an object property, you must implement the INotifyPropertyChanged interface for the object and report the value of the string to be modified.

 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 take place β€œautomatically” to all forms / text fields that are attached to the object. I would recommend this above by sending specific events, as this is the usual way to notify updates are bound to object properties.

0
source share

All Articles