Scanned value(using scanner) in the textbox

Geeth picture Geeth · May 24, 2010 · Viewed 17.1k times · Source

I am using Scanner (basic model) to scan the barcode. Scanned barcode will be captured in a textbox. In txtBarcode_TextChanged event, I am getting the barcode to access.

Problem:

If I click the scanner more than once, the barcode gets append with the previous value.

My Code:

protected void txtBarcode_TextChanged(object sender, EventArgs e)
{
    string txt = this.txtBarcode.Text;
    this.txtBarcode.Text = string.Empty;
}

Answer

Alistair Evans picture Alistair Evans · May 24, 2010

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.