我从表中读取了一些数据,之后我想编辑它,然后将编辑后的数据插入到数据库中。我编写了这段代码,但在运行之后,旧数据就插入到数据库中了。
我该怎么办?
这是我的代码;
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();
}
答案 0 :(得分:2)
您应该只从数据库中读取!Page.IsPostback
:
if (!IsPostBack)
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();
}
否则,您将覆盖所有更改并将控件绑定到旧值。
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx