0

In TextBox_Leave event i need to check whether numbers entered in textbox is in serial number or not.If it is not in order then i need to display a message as "number" is missing

For example :

In textbox i have entered 3 and click tab : I need to display message as "Number is not in order , number "1" and "2" is missing "

3
  • Just one question: Why would you want to do that? Commented Jun 26, 2009 at 11:51
  • 4
    that seem pretty basic stuff, homework? Commented Jun 26, 2009 at 11:55
  • This is weird feature, I think you can redesign this feature Commented Jun 26, 2009 at 11:57

5 Answers 5

7

I don't know whether this also works in c#2.0, this is my experience in c#3.0:

Why do you use TextBox_Leave for that? The Validating-event should be used for validating whether input is correct.

Combine using the Validating-event with using an ErrorProvider (you can just drag it from the toolbox onto the form) to set an error message: it will be displayed as a (blinking) exclamation mark in a red triangle.

An ErrorProvider can also block any submit-actions.

Sign up to request clarification or add additional context in comments.

Comments

1

One trick is to retain focus in the textbox when trying to leave (with TAB for instance) in case of some condition (missing number):

 private void textBox1_Leave(object sender, EventArgs e)
    {
        TextBox tb = (TextBox)sender;

        if (tb.Text == "3")
            tb.Focus();
    }

Assuming you are using a standard textbox. You could also use third party controls that where you can cancel an event (e.Cancel = true) on some condition.

1 Comment

Be careful with this kind of code, if you use this on multiple TextBoxes, you will create a loop of Focus you won't be able to break... An ErrorProvider is much better in this case.
1

Try using a Masked TextBox control and set a custom property for this type of field validation.

Comments

1

Alternatively you can also use Validating event of the text box.

  private void textBox1_Validating( object sender, CancelEventArgs e )
  {
      if ( textBox1.Text == "3" )
          e.Cancel = true;
  }

The text-box wont loose focus until it receives a valid input.

Comments

0

I will show you how to validate Validating WinForms TextBox (in C#).

  1. Create a function:

    public static void ChkBlankTextBoxes(object sender, string type)
    {
    
        if (sender is TextBox)
        {
            TextBox textbox = sender as TextBox;
            if (string.IsNullOrEmpty(textbox.Text))
            {
                MessageBox.Show("Please enter correct value value..");
                textbox.Focus();
    
            }
        }
    }
    
  2. Call to created function:

    ChkBlankTextBoxes(txt_userID, textBoxtype);
    
    ChkBlankTextBoxes(txt_password, textBoxtype);
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.