开发者

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 charac开发者_如何学Goters 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.


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.


You could have a timer and while no changes have occurred for say 1s to then do the lookup should it be 41 or 43 characters long.


I'd wrap the DB lookup call in a background worker class.
On the TextChanged event handler, the first thing I'd do is if the backgroundworker is working, I'd cancel it. Then if the text length is 41 or 43, I'd process the DB call in the backgroundworker.

This way if the user hits 41 characters, the call happens, if they type in a 42nd character the call is cancelled, however if they type in 43, then delete two characters (to get back down to 41 characters) you'll still be doing the proper lookup.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜