2011-11-29 109 views
0

我从表中读取了一些数据,之后我想编辑它,然后将编辑后的数据插入到数据库中。我编写了这段代码,但运行后,旧数据插入到数据库中。如何在从数据库中读取数据后编辑数据?

我该怎么办?

这是我的代码;

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 [email protected]"; 
    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 [email protected],[email protected] 
    where [email protected]"; 

    cmd1.Parameters.AddWithValue("@ChequeNo",ChequeNo_txt.Text); 
    cmd1.Parameters.AddWithValue("@ChequeDate", ChequeDate_txt.Text); 
    cmd1.ExecuteNonQuery(); 

} 
+8

为什么不接受您之前某些问题的答案? –

回答

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 [email protected]"; 
    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

+0

非常感谢你为我回贴作品 –