Dotnet Dotnet - 1 month ago 14
C# Question

How to handle Textbox leave event for only once

I have written a code to open a form if user enter value greater than Zero as follows

private void txtNoOfAddenda_Leave(object sender, EventArgs e)
{
string traceNo = string.Empty;
int i = 0;
if (!int.TryParse(txtNoOfAddenda.Text, out i))
{
MessageBox.Show("Enter numeric value betewwn(0-9999)");
txtNoOfAddenda.Focus();
}
else
{
if (i > 0)
{
traceNo = txtTraceNo.Text.Substring(8, 7);
frmAddenda frmAddenda = new frmAddenda(i, traceNo);
frmAddenda.ShowDialog();
}
}
}


This works fine but if i move back my tab and if again the textbox is leaving the same code executes i need only this to be fired one time can any one give me an Idea..

Answer

If you really want the event handler to fire only once, just unsubscribe from the event within the handler:

txtNoOfAddenda.Leave -= txtNoOfAddenda_Leave;

My guess is you want this code only within the code which shows the new form though - not if you show the message box.

Do you really want the user only to be able to show the new form once though? What if they close that form and come back to the one with the text box? Should there be no way of showing the other form again, e.g. if they've changed the value?

Comments