Search code examples
c#winformstextboxtextchanged

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?


Solution

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