-2
private void button1_Click(object sender, EventArgs e)
{
    int f = 1;

    SqlConnection con = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;

    con.Open();

    int bal = 0;

    string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
    cmd.CommandText = cmdstr;

    SqlDataReader dr = cmd.ExecuteReader();

    if (dr.Read())
        bal = int.Parse(dr[2].ToString());

    int draw = int.Parse(textBox1.Text);

    if(draw > bal)
    {
            MessageBox.Show("Insufficient balance!");
            return;
    }
    else
    {
            bal -= draw;
            cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";

            SqlDataAdapter da = new SqlDataAdapter();
            da.UpdateCommand = con.CreateCommand();
            da.UpdateCommand.CommandText = cmdstr;

            try
            {
                da.UpdateCommand.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                f = 0; 
            }

            if (f == 1)
                MessageBox.Show("Money withdrawn succesfully!");
            else
                MessageBox.Show("Enter correct amount!");
        }

        con.Close();

}

I am getting an "InvalidOperationException" while executing this program. I am not sure what the error is. Please help.

da.UpdateCommand.ExecuteNonQuery() is not getting executed

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Emil Sharier
  • 343
  • 1
  • 2
  • 9
  • 1
    Check the InnerException message from your main exception. But first. Stop here and read [why string concatenation to build an sql command](https://stackoverflow.com/a/332367/) is really bad – Steve Apr 23 '18 at 16:55

1 Answers1

0
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....        


        try
        {
            sqlcmd.ExecuteNonQuery();
....

Don't use adapter.

And yes. Faster of all try to close connection and open new one for update operation.

alerya
  • 3,125
  • 3
  • 28
  • 50