Reputation: 197
I use the following code to save a TextBox value into the database. However, when I insert the value it will save in a new row. How can I save it to the same row?
private void button1_Click(object sender, EventArgs e)
{
string pass = textBox1.Text;
sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=P3;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = sql;
cmd.CommandText = ("Insert [MyTable] ([MyColumn]) Values (@pass)");
cmd.Parameters.AddWithValue("@pass", pass);
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
Upvotes: 2
Views: 3449
Reputation: 6840
Use an update command instead of insert.
cmd.CommandText = "update YourTable set FieldName = YourValue where KeyField = YourKeyValue"
Upvotes: 4
Reputation: 247860
You need to use UPDATE instead of INSERT similar to this:
UPDATE yourTable
SET yourColumn = newValue
WHERE (your criteria needs to go here) ID = recordId
You need to create the UPDATE statement for your record. If your intention is to UPDATE all then your statement would be:
UPDATE yourTable
SET yourColumn = newValue
otherwise, you will want to tell it which records to UPDATE
UPDATE yourTable
SET yourColumn = newValue
WHERE ID = yourID
private void button1_Click(object sender, EventArgs e)
{
string pass = textBox1.Text;
sql = new SqlConnection(@"Data Source=PC-PC\PC;Initial Catalog=P3;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = sql;
cmd.CommandText = "UPDATE MyTable SET MyColumn = @pass WHERE id=@id"
cmd.Parameters.AddWithValue("@pass", pass);
cmd.Parameters.AddWithValue("@id", 1);
sql.Open();
cmd.ExecuteNonQuery();
sql.Close();
}
Here is a website with some samples explaining using ADO.NET:
Simple ADO.NET Database Read, Insert, Update and Delete using C#
Upvotes: 2