Scanned value(using scanner) in the textbox
The thing with barcode scanners is that they usually present themselves looking like a standard HID keyboard. Therefore, each new code scanned is effectively 'typed' after the previous one. A solution I have used in the past is to see how much time passes between key presses in that textbox. If it's more than 10 milliseconds (or around that value, I believe this was the largest amount of time taken for the scanner I was using to 'type' an entire code), then it's a new barcode, and you should delete everything before it.
I haven't got an IDE to hand, so most of the class/method names are probably way off, but something like an example:
DateTime lastKeyPress = DateTime.Now;
void txtBarcode_KeyPress(object sender, KeyPressEventArgs args)
{
if(((TimeSpan) (DateTime.Now - lastKeyPress)).TotalMilliseconds > 10)
{
txtBarcode.Text = "";
}
lastKeyPress = DateTime.Now;
}
I think that should do it. It works because the KeyPress event occurs before the character is appended, so you can clear the textbox first.
Edit: To set up, I guess that wherever you have txtBarcode.TextChanged += txtBarcode_TextChanged
, you instead have a txtBarcode.KeyPress += txtBarcode_KeyPress
. Check the event name is right though.
Edit 2:
jQuery Version:
Assuming this HTML (since you are using ASP, your source for the input tag will look different, but the output will still have the id
attribute, which is really the only one that matters):
<form action="" method="post">
<input type="text" name="txtBarcode" id="txtBarcode" />
</form>
Then this javascript works:
$(document).ready(function() {
var timestamp = new Date().getTime();
$("#txtBarcode").keypress(function(event)
{
var currentTimestamp = new Date().getTime();
if(currentTimestamp - timestamp > 50)
{
$(this).val("");
}
timestamp = currentTimestamp;
});
});
It seems that (at least in a web browser) 50 milliseconds is the required time to allow between characters. I've tested this in Firefox, Chrome and IE7.
try to change TextChanged event handler to kind of this:
txtBarcode.SelectionStart = 0;
txtBarcode.SelectionLength = txtBarcode.Text.Length;
It will select text in textbox after reading the code and rewrite it on other read. + it will be more suitable for users to copy it or change by hand
Most scanners can be programmed to "press enter" after scanning, check your user manual. You can use a Keypress or Keydown event handler to check for the "enter" key and use it as delimiter for your barcode. You can also use a special delimiting character if you prefer.
private void txtScan_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{
//Do something here...
txtScan.Text = "";
txtScan.Focus(FocusState.Programmatic);
e.Handled = true; //keeps event from bubbling to next handler
}
}