0

So, I'm quite new to C#. I have a a gridview row on my page. Once I edit the data, I want it updated also in the access database that is linked to it. I get this error: Syntax error in UPDATE statement. I think my date is the one to blame but still... I can't find out what I'm doing wrong. Here's the code for my update row function:

protected void OnUpdate(object sender, EventArgs e)
{
        GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
        string id = (row.Cells[0].Controls[0] as TextBox).Text;
        string nume = (row.Cells[1].Controls[0] as TextBox).Text;
        string prenume = (row.Cells[2].Controls[0] as TextBox).Text;
        string data = (row.Cells[3].Controls[0] as TextBox).Text;
        DataTable dt = ViewState["dt"] as DataTable;
        //dt.Rows[row.RowIndex]["ID"] = id;
        dt.Rows[row.RowIndex]["Nume"] = nume;
        dt.Rows[row.RowIndex]["Prenume"] = prenume;
        dt.Rows[row.RowIndex]["Data Nasterii"] = data;
        ViewState["dt"] = dt;
        GridView1.EditIndex = -1;

        OleDbConnection con;   // create connection
        OleDbCommand com;  // create command

        con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db\db1.mdb");

        con.Open();
        DateTime date = Convert.ToDateTime(data);
        com = new OleDbCommand("Update Table1 set Nume=" + nume + " , Prenume=" + prenume + ", Data Nasterii= @date where ID=" + id, con);
        com.Parameters.AddWithValue("@date", OleDbType.Date).Value=data;
        com.ExecuteNonQuery();
        con.Close();

        this.BindGrid();
        Response.Write("alert('DATA UPDATED')");

}

Can anyone help me?

1 Answer 1

4

If your column name has two words, you need to use square brackets with it. Like;

[Data Nasterii] = @date

But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

I see you parameterized your data value, parameterize your other values as well.

Also use using statement to dispose your OleDbConnection and OleDbCommand.

using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
    // Set your CommandText property.
    // Define and add your parameter values.
    // Open your OleDbConnection.
    // Execute your query.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.