Search code examples
c#textboxtextchanged

TextBox: TextChanged Event - Autovalidating when x chars have been entered


I have an app that reads in a barcode from a USB scanner. I want to do a DB lookup as soon as the barcode is entered in a particular textbox.

Clearly, I'm going to put my code in the TextChanged event handler, but I have a slight problem in that the barcode being read could be either 41 or 43 characters. The question is, how will I know which type of code is being entered. The scanner simply enters the code into whatever field has focus as a string of characters - as if it were entered by a keyboard - so I can't query the scanner to determine the code length.

I've thought of two approaches so far:

  • Detect first character, wait x.x seconds, and then do my lookup - allow enough time for a full code to be entered
  • Detect the 41st character, wait 0.x seconds and then do my lookup.

OK, I'm sure these will work OK, but are there any more eloquent solutions?

CONCLUSION:

Some useful suggestions, however Ondrej has inspired the simplest solution for my scenario. The 43 char codes have two characters that are fixed for all codes - the presence (or not) of these two characters means I know to wait if these two characters are present but only 41 characters are present.

I just need to confirm my suspicion that the 41 character codes can't have this pair of characters in this particular position - which I'm fairly sure is the case.


Solution

  • One option is to perform an Async lookup after the 41st character is read, while still waiting for two more characters in the UI thread. If you get a hit on that barcode you can stop waiting and show that result. Alternatively, if a 42nd character is entered while the lookup is in progress you can abort it and immediately begin a new lookup when the 43rd character is entered. This assumes, however, that no 43-character barcode begins with an existing 41-character barcode.

    I'd also look and see if the barcodes contain some pattern (for example: 41-char codes have an X as the 9th character and 43-char codes do not), and scan for that as it's being entered.