Noor
Noor

Reputation: 305

How to look for a specific amount of digits within texbox textChanged event in C#?

In my Windows Form Application, I want to implement a feature where the user has to fill in the serial number of a product that is when matched with any product in the database, the product must appear in a grid. I want to do so using textbox textChanged event.

I am confused in figuring out that either I must prevent firing the textChanged event before the textbox value matches any value in the database. Is there any way to make the textbox expect a specific amount of text or number (my serial numbers are going to be fixed length - like 10001, 10002, 10003) before running the remaining code for showing product in the grid?

Upvotes: 1

Views: 535

Answers (2)

Harald Coppoolse
Harald Coppoolse

Reputation: 30474

Consider the use of a [MaskedTextBox][1]. A MaskedTextBox is similar to a standard TextBox, except you define the format of the input text. This can be anything, letters, numbers, dashes, etc.

In your case you accept only input of five digits.

Use the windows forms designer to add a MaskedTextBox, or add one yourself:

this.maskedTextBox1 = new System.Windows.Forms.MaskedTextBox();
this.maskedTextBox1.Location = ...
this.maskedTextBox1.Size = ...
// etc. Advise: let forms designer do this

// accept only input of five digits:
this.Mask = "00000";

The operator sees an indication of the length of the requested input. It is impossible for the operator to type a non-digit. Event when all five digits are entered, but also while typing (TextChanged), so if desired you can implement autocompletion. You can even get notified if operator presses one invalid key, so you can inform the operator about the error

Upvotes: 1

Reza Aghaei
Reza Aghaei

Reputation: 125257

You can use TextLength property of the TextBox to get length of text. For example:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (textBox1.TextLength < 5)
        return;

    //Send query to database
}

Note: As it's also mentioned by Jimi in the comments, it's good idea to set MaxLength of TextBox to prevent entering more text.

Upvotes: 1

Related Questions