C# 通过编辑文本框C更新Sql数据库#

C# 通过编辑文本框C更新Sql数据库#,c#,sql-server,textbox,C#,Sql Server,Textbox,我有一个Winform,它通过编辑两个文本框Product Name和Product cost来更新SQL数据库,但是它不会更新数据库,下面是我的示例代码 private void simpleButton5_Click(object sender, EventArgs e) { string id = comboBox2.Items[comboBox2.SelectedIndex].ToString(); string name = txtPr

我有一个Winform,它通过编辑两个文本框Product Name和Product cost来更新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
,产品名称为
nvarchar(50)
,产品成本为
bigint

如果您有任何想法,请先将字符串值转换为int

string cost = txtProductCost.Text;
costval=int.Parse(cost)// costval is integer
接下来,更新数据库

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

似乎在转换过程中出现了错误,若数据库中的成本字段是bigint,那个么转换

string cost = txtProductCost.Text
string cost = txtProductCost.Text

Int64直接映射到BigInt

或者,如果是双精度,则转换


希望它对您有效。

您收到任何错误消息吗?您收到的错误消息是什么?您在数据库中的成本是使用double或int数据类型。没有错误,它只是不起作用。请将您的Sensive代码放入Try中,如果您没有收到任何错误,则必须存在转换错误,因为您的转换部分在Try之外,把它放在exect异常plz的try块中。请看我的答案,希望它能工作。它会给我一个异常“输入字符串的格式不正确”。我认为这是因为它是bigInteger,事实上,如果您使用AddWithValue,您不会将其独占地转换为int值,因为它也会自动转换和插入;)如果使用Bigint,则使用Convert.Toint64而不是Convert.Toint32
string cost = txtProductCost.Text
Double cost = Convert.ToDouble(txtProductCost.Text);