Search code examples
c#sqlsql-updatesql-server-celocal-database

Updating values in local dataBase error: CommandText property has not been initialized


I've created some sort of application that keeps a database of employees and their payments. It works well so far. But now I'm trying to implement an "update" feature, if there is some data that changes for specific user.

So I wrote the following code for the update, but I get this error:

CommandText property has not been initialized at line 105: "cmd.ExecuteNonQuery();"

Thanks !

var connString = @"Data Source=C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\Angajati.sdf";

using (var conn = new SqlCeConnection(connString))
{
    try
    {
        conn.Open();

        SqlCeCommand cmd = new SqlCeCommand();
        //conecteaza cmd la conn
        cmd.Connection = conn;

        //adauga parametru pt campul poza cu value image
        SqlCeParameter picture = new SqlCeParameter("@Poza", SqlDbType.Image);

        MemoryStream ms = new MemoryStream();
        pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
        byte[] a = ms.GetBuffer();
        ms.Close();

        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@Poza", a);

        var query = "UPDATE info SET Nume='" + textBox5.Text + "' AND Prenume='" + textBox4.Text + "' AND Data='" + dateTimePicker1.Value.ToShortDateString() + "' AND Proiect='" + textBox1.Text + "' AND Schimburi='" + label10.Text + "' AND Poza=@Poza AND Acord='" + textBox2.Text + "' AND Baza='" + textBox3.Text + "'  WHERE Nume='" + label8.Text + "' AND Prenume='" + label5.Text + "'";

        cmd.ExecuteNonQuery();

        MessageBox.Show("Salvat cu succes!");
        this.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Solution

  • You must set cmd.CommandText

                    //Codes
                    cmd.CommandText = query;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Salvat cu succes!");
                    this.Close();