I updated sql data base using c# text box but all records updated with same value what I entered in that text box. where I did wrong.
Below My code
private void btnsave_Click(object sender, EventArgs e)
{
try
{
string connectionString = (@"Data Source = M2\SQL2016; Initial Catalog = inventoryDB; Integrated Security = True");
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE companyDB SET compname=@label3", conn))
{
cmd.Parameters.AddWithValue("@label3", cmpname.Text);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Not Updated");
}
You should set the where clause here to filter what records should be updated. The WHERE clause is used to extract only those records that fulfill a specified criterion. See the following example which filters based on id column:
new SqlCommand("UPDATE companyDB SET compname=@label3 where id = @id", conn))
And:
cmd.Parameters.AddWithValue("@id", id.Text);
Although specify the type directly and use the Value
property is more better than AddWithValue
:
cmd.Parameters.Add("@label3", SqlDbType.VarChar).Value = cmpname.Text;
Also check here: Can we stop using AddWithValue() already?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.