Reputation: 2499
I make a program that saves and update a data from the database, I can save and read data, I can also update but the problem is, I can't select the "ID"
as the index, here is my sample code using "ID"
as the index,
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = @firstname, LastName = @lastname, Age = @age, Address = @address, Course = @course WHERE [ID] = @id";
cmd.Parameters.AddWithValue("@id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("@firstname", textBox1.Text);
cmd.Parameters.AddWithValue("@lastname", textBox2.Text);
cmd.Parameters.AddWithValue("@age", textBox3.Text);
cmd.Parameters.AddWithValue("@address", textBox4.Text);
cmd.Parameters.AddWithValue("@course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();
}
and here is my update code that works, but the index is the "firstname"
,
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = @firstname, LastName = @lastname, Age = @age, Address = @address, Course = @course WHERE FirstName = @firstname";
//cmd.Parameters.AddWithValue("@id", int.Parse(label7.Text));
cmd.Parameters.AddWithValue("@firstname", textBox1.Text);
cmd.Parameters.AddWithValue("@lastname", textBox2.Text);
cmd.Parameters.AddWithValue("@age", textBox3.Text);
cmd.Parameters.AddWithValue("@address", textBox4.Text);
cmd.Parameters.AddWithValue("@course", textBox5.Text);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
{
MessageBox.Show("Update Success!");
cn.Close();`
}
It works but the problem is I can't update the "FirstName"
, Is there a way that I can also update the Firstname? or use the "ID"
as the index? thanks
Upvotes: 6
Views: 28923
Reputation: 31
You should add the following code after the last line of ID
:
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE Records SET FirstName = @firstname, LastName = @lastname, Age = @age, Address = @address, Course = @course WHERE [ID] = @id";
cmd.Parameters.AddWithValue("@firstname", textBox1.Text);
cmd.Parameters.AddWithValue("@lastname", textBox2.Text);
cmd.Parameters.AddWithValue("@age", textBox3.Text);
cmd.Parameters.AddWithValue("@address", textBox4.Text);
cmd.Parameters.AddWithValue("@course", textBox5.Text);
cmd.Parameters.AddWithValue("@id", int.Parse(label7.Text));
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery(); {
MessageBox.Show("Update Success!");
cn.Close();
}
Upvotes: 3
Reputation: 48129
I don't know what database you are going against, however, I don't know if the OleDB is being picky on the ordinal sequence of your parameters. ie: Have you tried putting your "ID" parameter in the last position to match the actual order of the fields of your update command? I don't know if it's throwing it out.
Upvotes: 7