I have a class which is a UserControl:
public partial class MyView : System.Windows.Forms.UserControl
This interface has various components for user input. To show the issue I'm having, only one is needed to show, so, in MyView.Designer.cs
:
internal System.Windows.Forms.TextBox txtMyNumber;
This starts out as blank. So then user enters a number in the TextBox.
Then the user clicks the X in the upper right corner, which calls MyView.OnClose()
:
protected void OnClose()
{
string myNumber = txMyNumber.Text;
}
Here I want to check if any data has been entered. However, txtMyNumber
does not show what the user entered, it is still blank. So it appears when the user clicks on the X, it is off the Form and doesn't know about the values entered.
How can these values be accessed?
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.OnClose();
if (_presenter != null)
_presenter.Dispose();
if (components != null)
components.Dispose();
}
base.Dispose(disposing);
}
Another method is to subscribe to the container Form's FormClosing
event and save what needs to be saved when the parent Form begins its shut down process.
The Form's event can be subscribed in the Load()
event of the User Control, so you're sure that all the handles are already created:
private Form MyForm = null;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.MyForm = this.FindForm();
this.MyForm.FormClosing += this.OnFormClosing;
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
Console.WriteLine("My Form is closing!");
string myNumber = txMyNumber.Text;
}
This method is more useful if the UC needs to know something else about its Form.
Another, quite similar, way is to suscribe to the User Control's OnHandleDestroyed
event.
protected override void OnHandleDestroyed(EventArgs e)
{
Console.WriteLine("I'm being destroyed!");
string myNumber = txMyNumber.Text;
base.OnHandleDestroyed(e);
}