Passing a Variable Between Forms in Windows Forms
In Windows Forms applications, passing data between forms can be achieved using delegates and events. The problem arises when one form, the "child" form, requires accessing a variable from the "parent" form.
To solve this, consider utilizing delegates to send data from the parent form to the child form. In the parent form, define a delegate and an event handler for it. When the button to open the child form is clicked, create an event argument object carrying the variable value and raise the event.
In the child form, subscribe to the event in the constructor. When the event occurs, retrieve the variable value from the event argument object. Modify the child form's controls or properties to display the variable text dynamically.
Here's an example code in C#:
// Parent Form public partial class MainForm : Form { public delegate void PageInfoHandler(object sender, PageInfoEventArgs e); public event PageInfoHandler PageInfoRetrieved; private void toolStripBtnSettings_Click(object sender, EventArgs e) { PageInfoEventArgs args = new PageInfoEventArgs(SomeString); OnPageInfoRetrieved(args); SettingsForm settingsForm = new SettingsForm(); settingsForm.ShowDialog(); } private void OnPageInfoRetrieved(PageInfoEventArgs args) { if (PageInfoRetrieved != null) PageInfoRetrieved(this, args); } } // Child Form public partial class SettingsForm : Form { private string m_Data; // Variable to store the passed value public SettingsForm() { InitializeComponent(); Subscribe to PageInfoRetrieved event } private void OnPageInfoRetrieved(object sender, PageInfoEventArgs e) { m_Data = e.Value; // Update controls or properties in this form } public string Data => m_Data; // Expose the variable as a property }
The above is the detailed content of How Can I Pass a Variable Between Forms in Windows Forms Applications?. For more information, please follow other related articles on the PHP Chinese website!