C# 如何显示产品的数量?
我试着数一数产品的数量,我怎样才能做到这一点(在图像中)?我希望,你能理解我。我的代码不起作用。C# 如何显示产品的数量?,c#,winforms,C#,Winforms,我试着数一数产品的数量,我怎样才能做到这一点(在图像中)?我希望,你能理解我。我的代码不起作用。 这是我的代码: private void button1_Click(object sender, EventArgs e) { int i=1; SqlCommand seldb = new SqlCommand("Select * from Product where barcode=" + textBox1.Text, conn);
这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
int i=1;
SqlCommand seldb = new SqlCommand("Select * from Product where barcode=" + textBox1.Text, conn);
conn.Open();
seldb.ExecuteNonQuery();
SqlDataReader read = seldb.ExecuteReader();
while (read.Read() == true)
{
dataGridView1.Rows.Add(read.GetValue(0), read.GetValue(1), read.GetValue(2), i);
for (int j=0;j<=dataGridView1.Rows.Count-1;j++)
{
if (textBox1.Text == dataGridView1.Rows[j].Cells[2].Value)
{
dataGridView1.Rows[j].Cells[3].Value = i;
}
}
i++;
}
conn.Close();
}
private void按钮1\u单击(对象发送者,事件参数e)
{
int i=1;
SqlCommand seldb=新SqlCommand(“从产品中选择*,其中条形码=“+textBox1.Text,conn”);
conn.Open();
seldb.ExecuteNonQuery();
SqlDataReader read=seldb.ExecuteReader();
while(read.read()==true)
{
dataGridView1.Rows.Add(read.GetValue(0)、read.GetValue(1)、read.GetValue(2)、i);
对于(int j=0;j尝试更改SQL查询以聚合数量
用这个命令替换您的命令
SqlCommand seldb = new SqlCommand("Select ProductId, Name, Barcode, COUNT(*) as Quantity from Product where barcode =" + textBox1.Text + " Group By ProductId, Name, Barcode", conn);
实际上,您应该同时使用和语句
然后,您将用新的Quantity
列替换i
值
注意:不要忘记Bobby表-在Product表中有IdProduct、Name和Barcode。但在datagrid中没有QuantityInWnat以显示名称计数,其中textBox1.Text==dataGridView1.Rows[j]。Cells[2].value这是一个正确的解决方案。此外,他/她可以使用Count
而不是Sum
,还可以使用参数化查询来避免SQL注入。+1.@S.Akbari打电话给Count
,很好地解决了Quantity
不在数据库中的问题。我用该建议更新了答案。对不起,我该怎么办是否“将i
值替换为新的Quantity
列”?确保将该值作为参数从文本框中传递,而不仅仅是将字符串串联在一起。清除数据库中的输入非常重要。