我有两个数据表 Table_1 和 Table_2。我的代码有什么问题?我不能在 Table_2 中添加 Table_1 的库存总和?
当我更新一次时,我有一个正确的输出。
http://tinypic.com/view.php?pic=1632bs&s=5
当我再次按下更新按钮时,它只更新第一行,如下图所示:
http://tinypic.com/r/350p6hd/5
private void txtid_TextChanged(object sender, EventArgs e)
{
SqlConnection csq = new SqlConnection("workstation id=;initial catalog=iridadb; integrated security=SSPI");
SqlDataAdapter dsaq = new SqlDataAdapter();
DataSet dsq = new DataSet();
dsaq.SelectCommand = new SqlCommand("Select * from Table_1 where left(id, " + txtid.Text.Length + ") = '" + txtid.Text + "' order by ItemID ASC", csq);
dsq.Clear();
dsaq.Fill(dsq);
dataGridView1.DataSource = dsq.Tables[0];
dataGridView1.AllowUserToAddRows = false;
bindDataGridView2();
}
public void bindDataGridView2()
{
SqlConnection csq = new SqlConnection("workstation id=;initial catalog=iridadb; integrated security=SSPI");
SqlDataAdapter dsaq = new SqlDataAdapter();
DataSet dsq = new DataSet();
dsaq.SelectCommand = new SqlCommand("Select * from Table_2 ", csq);
dsq.Clear();
dsaq.Fill(dsq);
dataGridView2.DataSource = dsq.Tables[0];
dataGridView2.AllowUserToAddRows = false;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
for (int i = 0; i <= dataGridView1.Rows.Count - 1; i++)
{
if (!dataGridView1.Rows[i].IsNewRow)
{
SqlConnection connan = new SqlConnection("DATA SOURCE=;initial catalog=iridadb; integrated security=SSPI");
SqlDataAdapter danan = new SqlDataAdapter();
danan.UpdateCommand = new SqlCommand("UPDATE Table_2 SET Stock = @Stock WHERE itemID = @itemID", connan);
danan.UpdateCommand.Parameters.Add("@itemID", SqlDbType.VarChar).Value = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value).ToString();
danan.UpdateCommand.Parameters.Add("@Stock", SqlDbType.VarChar).Value = (Double.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()) + Double.Parse(dataGridView2.Rows[i].Cells[1].Value.ToString())).ToString();
connan.Open();
danan.UpdateCommand.ExecuteNonQuery();
connan.Close();
bindDataGridView2();
}
}
}