开发者

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


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?


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.


You can keep a instance variable:

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


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();
    }
  }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜