Search code examples
c#winformsrfid

Clear textbox when tap RFID card?


I got 2 RFID cards, with different values e.g 123 and 456. When I click on textbox1, and then tap the first card into a machine, the textbox1.text will give me a text of 123.

The question is how can I clear the first card value when I tap the second card to machone. what event on the textbox1 should I use, so when I tap the second card it only give me 456.

The code which the device sends has a specific lengths, for example 10 characters.

Currently using the code which I have tried, after I tap the the first card, and then tap the second card, the textbox1.text become 123456, while I expect it to show 123 for first card and 456 for second card.

private void textEdit1_EditValueChanged(object sender, EventArgs e)
{
    string text1;
    text1 = textEdit1.Text;
    if (string.IsNullOrEmpty(text1)) return;

    if (text1.Length == 10)
    {              
        getcodestudent(text1);
        textEdit1.Text = string.Empty;
        textEdit2.Focus();
        textEdit1.Focus();
        cektap();
        if (tap == 0 && tap2 == 0)
        {
            MessageBox.Show("member not registered on this class");
        }
    }            
}  

When I debug it. The event run twice, because I set the textedit.Text to empty it ran over (loop) 1 times. conclusion : When I debug the program, after it reach the end of code messagebox.show it loop back to textEdit1.Text = string.Empty; and again run the cektap() method. only loop once.


Solution

  • Bar-code scanners or such devices usually send key strokes. So you can handle KeyPress event of TextBox and check if the length of Text is the specific length which you expect, then clear the Text:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (this.textBox1.TextLength == 10)
            this.textBox1.Text = "";
    }
    

    Also some devices send an extra Enter key at the end of sequence which can be handled and be used to run default action of Form or changing focus or something else. For example:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Return)
        {
            //Do Something and the select all texts to prepare text box for next card
            this.textBox1.SelectAll();
        }
    }