文本框不能扫描多个号码,只能扫描一个号码

时间:2019-01-29 13:00:47

标签: c# barcode barcode-scanner keydown

当我扫描条形码时,它仅显示数据库中的一个数字条形码。我的其他长条码没有显示

private void textBox4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                if ((e.KeyCode != Keys.Enter) || (textBox4.Text.Length == 0))
                {
                    return;
                }

                conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\Database\book1.mdf;Integrated Security=True;Connect Timeout=30");
                conn.Open();
                SqlDataAdapter adp = new SqlDataAdapter("SELECT productid,ProductName,Description,Stock,UOM,Price from ProductTable where productId='" + textBox4.Text + "'", conn);
                DataTable dt = new DataTable();
                adp.Fill(dt);

                foreach (DataRow item in dt.Rows)
                {
                    int i = dataGridView1.Rows.Add();
                    DataGridViewRow row = dataGridView1.Rows[i];
                    row.Cells[0].Value = item[0].ToString();
                    row.Cells[1].Value = item[1].ToString();
                    row.Cells[2].Value = item[2].ToString();
                    row.Cells[3].Value = item[3].ToString();
                    row.Cells[4].Value = item[4].ToString();
                    row.Cells[5].Value = item[5].ToString();
                }
                conn.Close();    
            }
            textBox4.Text=" ";
        }

页面截图:

-https://ibb.co/xHsg198

2 个答案:

答案 0 :(得分:2)

删除行

textBox4.Text=" ";

因为它会擦除您的条形码数字。当条形码扫描完成并发送Keys.Enter时,文本框仅包含一位数字。

如果您需要在搜索后清除文本框,请将此行放在条件语句的末尾

private void textBox4_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //...
        conn.Close();
        textBox4.Text=" ";
    }
}

答案 1 :(得分:0)

就像@Alexander说的那样,删除:

textBox4.Text = " ";

您还可以将捕获事件更改为textBox4_Validated,只有在离开文本框后才会发生(您可以离开KeyDown,并且仅捕获Enter键以强制验证文本框)。

如果您的目标只是数字,则可以添加测试以验证它是否仅是数字。

另一个提示,如果您可以对扫描仪进行编程,则应在扫描的字符串的末尾添加特定的字符(例如'\ n'或您永远不会在真实代码中找到的任何字符)。这样,您可以连续扫描所有代码,然后分割最后的字符串并在foreach中执行代码。

最后一点,在这里并不是很重要,当您按下此处的按键只是为了执行一些代码,而又不想将keyPress有效地添加到文本框中时,或者添加以下内容:

e.SuppressKeyPress = true;
e.Handled = true;

我不确定这到底是做什么的,但是如果我做得很好,第一行将表明keyPress好像从未发生过,第二行告诉系统keyPress已被正确使用和处理,因此不必再干预了。

希望这对您有帮助

相关问题