【发布时间】:2019-08-20 00:04:43
【问题描述】:
当在 form1 上扫描条形码时,我调用数据库以获取此条形码的项目并使用预先填充的数据打开 form2。
如果我使用文本更改事件,那么它会产生与一个条形码中的数字一样多的次数。
我无法检查条形码的长度,因为它可能每次都不同。
当条形码被扫描时,我应该使用哪个事件来只拨打一个电话?
我尝试了 TextChanged、KeyPress、KeyDown 事件,但它们都被多次调用。
private void txt_Barcode_TextChanged(object sender, EventArgs e)
{
con.Open();
GenerateInvoice gn = new GenerateInvoice();
string query = "SELECT * FROM dbo.Inventory WHERE Barcode = '" + txt_Barcode.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (DR1.Read())
{
gn.txt_Barcode.Text = dr["Barcode"].ToString();
gn.txt_ProductName.Text = dr["ProductName"].ToString();
gn.txt_Price.Text = dr["SellingPrice"].ToString();
gn.txt_QTY.Text = 1.ToString();
gn.txt_Total.Text = dr["SellingPrice"].ToString();
}
con.Close();
}
我愿意使用文本框来捕获 form1 上的条形码(我将在 UI 上隐藏它)
【问题讨论】:
-
条形码扫描仪在代码完成后发送一个 Enter 键。此外,大多数扫描仪还可以配置为同时发送前缀、后缀或同时发送条形码(例如,识别发送条形码的扫描仪)。使用 KeyDown 事件。例如,
if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; //( process) } -
此外,您的代码的 sql 方面还有一些不足之处。摆脱硬编码查询,使用参数化,使用
using()块检查适当的资源清理。 -
当您像使用键盘一样使用条形码扫描仪时,理想情况下只想在看到此事件后触发事件:(去抖动和节流)stackoverflow.com/questions/25991367/…