I read some data from a table and after that I want to edit it, and then insert edited data to the database. I wrote this code but after runing it, old data inserts into database.
What should I do?
Here is my code;
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = new SqlConnection(Class1.CnnStr);
SqlDataReader reader;
cmd.CommandText = "select ChequeNo,ChequeDate from table where Number=@Number";
cmd.Connection.Open();
cmd.Parameters.AddWithValue("@Number", Number_lbl.Text);
reader = cmd.ExecuteReader();
if (reader.Read())
{
ChequeNo_txt.Text = reader["ChequeNo"].ToString();
ChequeDate_txt.Text = reader["ChequeDate"].ToString();
reader.Close();
}
cmd.Connection.Close();
}
protected void SAVE_bt_Click(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = new SqlConnection(Class1.CnnStr);
cmd1.Connection.Open();
cmd1.Parameters.AddWithValue("@Number", Number_lbl.Text);
cmd1.CommandText ="update table set chequeNo=@ChequeNo,ChequeDate=@ChequeDate
where Number=@Number";
cmd1.Parameters.AddWithValue("@ChequeNo",ChequeNo_txt.Text);
cmd1.Parameters.AddWithValue("@ChequeDate", ChequeDate_txt.Text);
cmd1.ExecuteNonQuery();
}
You should only read from database if
!Page.IsPostback:Otherwise you are overwriting all changes and bind the controls to the old values.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx