【发布时间】:2016-01-18 01:19:14
【问题描述】:
我有一个名为 Product 的数据库表。里面有 ID、ProductName、Brand、Description、Price、Cost 和 Count。我想使用文本框更新 Count 值。
例如,如果我在文本框中输入一个值,并且Count下已经有10,那么更新后的值应该是文本框中的值+10。
这是我的代码:
protected void btnAdd_Click(object sender, EventArgs e)
{
string productName = ddlName.Text;
string quantity = tbQuantity.Text;
string strConnectionString = ConfigurationManager.ConnectionStrings["TrimberlandConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "Select ProductName FROM Product WHERE ProductName = @ProductName";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("@ProductName", productName);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
addStocks(productName, quantity);
reader.Close();
myConnect.Close();
}
private void addStocks(string productName, string quantity)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["TrimberlandConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE Product SET Count = Count + 1 ";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("@ProductName", productName);
cmd.Parameters.AddWithValue("@Count", quantity);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Stocks have successfully been added.");
}
myConnect.Close();
}
【问题讨论】:
-
有效吗?如果不是,有什么问题?您收到任何错误代码吗?在任何特定的行上?
-
@Ian 它可以工作,但它只会加 1。我需要它来添加我在文本框中键入的值。但我不确定如何修改查询。
-
@GrantWinney addStocks 中的 strCommandText。它有效,但我需要它来添加我在文本框中键入的值,而不仅仅是 +1。
标签: c# asp.net sql-server database shopping-cart