System.Data.SqlClient.SqlException 发生更新 table

System.Data.SqlClient.SqlException occurs for updating table

为了更新Customer/PartyId,我要求用户填写CP_id和表单的其他元素,然后我在CP_id的基础上更新数据库中的数据:

if (CP_id.Text != " ")
{
    string cpid=CP_id.Text;
    string query = "Update tbl_partyinfo set Name = @Name, Addrss = @Addrss, Cntct_No = @Cntct_No where CP_id = cpid";

    using (SqlConnection connection1 = new SqlConnection(conn))
    {
        connection1.Open();

        using (SqlCommand insertCommand = new SqlCommand(query, connection1)) 
        {
            insertCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtname.Text;
            insertCommand.Parameters.Add("@Addrss", SqlDbType.VarChar).Value = txtAddrss.Text;
            insertCommand.Parameters.Add("@Cntct_No", SqlDbType.VarChar).Value = txtcontact.Text;

            //make sure you open and close(after executing) the connection
            var rowsaffected = insertCommand.ExecuteNonQuery();

            connection1.Close();

            MessageBox.Show("Id no."+CP_id.Text +" Updated.");
         }
     }
}
else
{
    MessageBox.Show("Please identify Id before updating");
}

但是我得到一个错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Invalid column name 'cpid'

我收到此错误,但没有替代方法来获得此类功能。

CP_id=cpid

这需要像这样的另一个绑定参数:CP_id=@cpid 并且您需要另一行添加此参数及其值。其他三个你已经做了,第四个也不会太难。