Developer
Developer

Reputation: 8636

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..

Upvotes: 2

Views: 4547

Answers (5)

Mike Cheel
Mike Cheel

Reputation: 13106

I just had this issue and solved it by moving my code out of the Leave event and into the into the Validated event.

Upvotes: 0

KBoek
KBoek

Reputation: 5975

Define the form variable outside your event handler method, and inside the method check if the form has been instantiated before. You might also run a check to see if the form is open.

private frmAddenda _frmAddenda

private void txtNoOfAddenda_Leave(object sender, EventArgs e)
{
  ...
  else
  {
    if (i > 0 && _frmAddeda == null)
    {
      traceNo = txtTraceNo.Text.Substring(8, 7);
      frmAddenda frmAddenda = new frmAddenda(i, traceNo);
      frmAddenda.ShowDialog();
    }
  }
}

Upvotes: 0

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

Inside you method, add the following line:

txtNoOfAddenda.Leave -= txtNoOfAddenda_Leave;

This will unregister the event handler and make sure it does not get called again later on.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500145

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?

Upvotes: 8

The Scrum Meister
The Scrum Meister

Reputation: 30111

You can keep a instance variable:

private bool eventRan = false;
private void txtNoOfAddenda_Leave(object sender, EventArgs e)
{
    if(eventRan) return;
    eventRan  = true;
    ....

Upvotes: 1

Related Questions