I have created a Windows Form which emerges as pop up, and it represents MessageBox
with input field (as there is not something like this already existing in C#
). Now, I want to forbid this form closing if the input field is left empty. For that scenario, I am adding FormClosing
event:
private void AdditionalForm(TransferClass transfer)
{
Form newForm = new Form()
{
Width = 570,
Height = 230,
FormBorderStyle = FormBorderStyle.FixedToolWindow,
ForeColor = Color.WhiteSmoke,
Font = new Font("Century Gothic", 10, FontStyle.Bold),
Text = "New form",
StartPosition = FormStartPosition.CenterScreen
};
Label lblNew = new Label() { Left = 20, Top = 20, AutoSize = true, BackColor = Color.Transparent, ForeColor = Color.Firebrick, Font = new Font("Century Gothic", 12), Text = "SOME TEXT" };
TextBox txtNew = new TextBox() { Left = 20, Top = 100, Width = 500, BackColor = Color.Firebrick, ForeColor = Color.WhiteSmoke, Font = new Font("Century Gothic", 12) };
Button btnNew = new Button() { Text = "CLICK ME", Left = 20, Width = 500, Height = 50, Top = 140, DialogResult = DialogResult.OK, BackColor = Color.Firebrick, ForeColor = Color.WhiteSmoke, Font = new Font("Century Gothic", 12), FlatStyle = FlatStyle.Flat };
btnNew.Click += (sender, e) => { newForm.Close(); };
newForm.Controls.Add(txtNew);
newForm.Controls.Add(btnNew);
newForm.Controls.Add(lblNew);
newForm.AcceptButton = btnNew;
newForm.FormClosing += NewForm_FormClosing;
if (newForm.ShowDialog() == DialogResult.OK)
{
//some function
}
}
private void NewForm_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Input field not be empty!", "ERROR", MessageBoxButtons.OK);
e.Cancel = false;
}
And this works fine if user clicks X button on a form, or ALT + F4
on a keyboard, event is going to be triggered and won't let him close the form. But if clicks on a button, the message is going to be shown also, no matter input field is empty or not, and the form is going to be closed also.
First, I wan't to prevent message from showing if btnNew
was clicked and txtNew
is not empty, and I can do that if I cast sender
in event to button
and check the name of a button. But the problem is that I don't know how can I access txtNew
from FormClosing
event to check if it is empty or not?