Home > Net >  how to update weight in database
how to update weight in database

Time:10-27

private void btn_Update_Click(object sender, EventArgs e)
{
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "update MyWeight set Weight='"   txt_Weight.Text   "'where Name='"   txt_Name.Text   "'";
    string a = (string)cmd.ExecuteScalar();
    con.Close();

    if (a != null)
    {
        cmd.ExecuteNonQuery();
        con.Close();

        display_data();
        MessageBox.Show("Weight updated successfuly!!!");
    }
    else
    {
        con.Close();

        display_data();
        MessageBox.Show("Not updated!!!");
    }
}

I tried to update the weight into the database, but the database keeps saying that it is not updated.

CodePudding user response:

Try like this:

        bool updated;
        con.Open();
        using (SqlCommand cmd = con.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "update MyWeight set Weight=@Weight where Name=@Name";


            cmd.Parameters.Add(new SqlParameter("Weight", txt_Weight.Text));
            cmd.Parameters.Add(new SqlParameter("Name", txt_Name.Text));

            updated = (cmd.ExecuteNonQuery() > 1);

            con.Close();
        }
            

        if (updated)
        {
            display_data();
            MessageBox.Show("Weight updated successfuly!!!");
        }
        else
        {
            display_data();
            MessageBox.Show("Not updated!!!");
        }

CodePudding user response:

It makes more sense to use ExecuteNonQuery for update operations in general because you don't expect any results.

Have you checked the table to see if it did update the row?

Why are you executing the same command with ExecuteNonQuery inside the if statement?

  •  Tags:  
  • c#
  • Related