2013-04-25 117 views
0

我有一個WinForm通過編輯兩個TextBox產品名稱和產品成本更新SQL數據庫,但是它不更新數據庫,這裏是我的示例代碼更新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。 任何想法我會感謝

+1

你有任何錯誤信息接收? – 2013-04-25 11:43:35

+1

你得到的錯誤信息是什麼,你在數據庫中的成本是雙倍或者是int數據類型。 – Rahul 2013-04-25 11:50:10

+0

沒有錯誤,它只是不起作用 – user2102572 2013-04-25 11:55:56

回答

0

首先,將字符串值轉換成int

string cost = txtProductCost.Text; 
costval=int.Parse(cost)// costval is integer 

接下來,更新數據庫

cmd.Parameters.AddWithValue("@Product_Price", costval); 
+0

它給了我一個例外「輸入字符串的格式不正確。」 – user2102572 2013-04-25 11:55:06

+0

我認爲這是bigInteger不是int – user2102572 2013-04-25 11:55:27

+0

如果是這樣,將其轉換爲正確的格式,並嘗試 – 2013-04-25 11:57:29

1

看來你在轉換一個錯誤,如果你的成本字段在數據庫中是bigint,然後轉換成

string cost = txtProductCost.Text 

Int64 cost = Convert.Toint64(txtProductCost.Text); 

Int64直接映射到BigInt。

或者如果它是雙然後將其轉換

string cost = txtProductCost.Text 

Double cost = Convert.ToDouble(txtProductCost.Text); 

希望它爲你工作。

+1

如果您使用Bigint然後使用Convert.Toint64而不是Convert.Toint32 – Rahul 2013-04-25 11:57:22

+0

非常感謝你拉胡爾 – user2102572 2013-04-25 12:16:35