[英]Update Sql database via editing Textbox C#
我有一個Winform,它通過編輯兩個TextBox產品名稱和產品成本來更新SQL數據庫,但是它不會更新數據庫,這是我的示例代碼
private void simpleButton5_Click(object sender, EventArgs e)
{
string id = comboBox2.Items[comboBox2.SelectedIndex].ToString();
string name = txtProdName.Text;
string cost = txtProductCost.Text;
cn.Open();
string query = "UPDATE [Product1] SET [Product_Name]= @Product_Name,[Product_Cost]= @Product_Cost where [Product_ID]= @Product_ID";
SqlCommand cmd = new SqlCommand(query, cn);
cmd.Parameters.AddWithValue("@Product_ID", id);
cmd.Parameters.AddWithValue("@Product_Name", name);
cmd.Parameters.AddWithValue("@Product_Price", cost);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Update Succesfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
cn.Close();
}
id的數據類型為char
,Product_Name為nvarchar(50)
,Porduct_Cost為bigint
。 任何想法,我將不勝感激
似乎您在轉換中出錯,如果數據庫中的cost字段為bigint,則進行轉換
string cost = txtProductCost.Text
至
Int64 cost = Convert.Toint64(txtProductCost.Text);
Int64直接映射到BigInt。
或者如果是Double,則進行轉換
string cost = txtProductCost.Text
至
Double cost = Convert.ToDouble(txtProductCost.Text);
希望對你有效。
首先,將字符串值轉換為int
string cost = txtProductCost.Text;
costval=int.Parse(cost)// costval is integer
接下來,更新數據庫
cmd.Parameters.AddWithValue("@Product_Price", costval);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.