2011-11-29 34 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

非常感謝你爲我回貼作品 –