2011-05-31 43 views
0

我有一個問題,當我想以更新數據庫中的行。更新的頁面也添加了一個客戶端,但問題是當頁面加載檢測到更新按鈕被按下時,它似乎繼續加載變量,我無法更新我的數據庫。加載事件問題

public partial class CustomerInput : System.Web.UI.Page 
{ 
    string update, Id, Name, Address, Suburb, Postcode, Age, Email; 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     update = Request.QueryString["Update"]; 
     if (update == "true") 
     { 
      SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer"); 
      Button1.Text = "Update"; 

      Id = Request.QueryString["Id"]; 
      connection.Open(); 

      SqlCommand command = new SqlCommand("Select * from Customer where Id = " + Id, connection); 

      SqlDataReader read = command.ExecuteReader(); 
      read.Read(); 
      TextBox1.Text = read[1].ToString(); 
      TextBox2.Text = read[2].ToString(); 
      TextBox3.Text = read[3].ToString(); 
      TextBox4.Text = read[4].ToString(); 
      TextBox5.Text = read[5].ToString(); 
      TextBox6.Text = read[6].ToString(); 

      connection.Close(); 
      update = string.Empty; 
     } 

    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer"); 

     if (Button1.Text == "Update") 
     { 
      connection.Open(); 
      SqlCommand command; 

      Name = TextBox1.Text; 
      Address = TextBox2.Text; 
      Suburb = TextBox3.Text; 
      Postcode = TextBox4.Text; 
      Age = TextBox5.Text; 
      Email = TextBox6.Text; 


      command = new SqlCommand("UPDATE Customer SET Name = " + "'" + Name + "', " + "Address = " + "'" + Address + "', " + "Suburb = " + "'" + Suburb + "', " 
        + "Postcode = " + "'" + Postcode + "', " + "Age = " + "'" + Age + "', " + "Email = " + "'" + Email + "' " + "Where Id =" + Id, connection); 

      command.ExecuteNonQuery(); 
      connection.Close(); 

     } 
     if (Button1.Text == "New Client") 
     { 
      Name = TextBox1.Text; 
      Address = TextBox2.Text; 
      Suburb = TextBox3.Text; 
      Postcode = TextBox4.Text; 
      Age = TextBox5.Text; 
      Email = TextBox6.Text; 

      Response.Write("Blah"); 

      SqlCommand command = new SqlCommand("INSERT INTO Customer VALUES (" + "'" + Name + "'" + ", " + "'" + Address + "'" + ", " + "'" + Suburb + "'" + ", " 
       + "'" + Postcode + "'" + ", " + "'" + Age + "'" + ", " + "'" + Email + "'" + ")", connection); 

      command.ExecuteNonQuery(); 
     } 

     Button1.Text = "New Client"; 
    } 
} 

}

+0

'它似乎繼續加載變量'什麼變量?爲什麼你無法更新你的數據庫?在Page_Load中 – 2011-05-31 15:02:39

+0

檢查[!Page.IsPostback(http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback%28v=vs.71%29.aspx)。 – 2011-05-31 15:04:29

回答

2

在你的頁面加載事件,你需要添加一個if語句來檢查,如果這是第一次加載頁面開始:

例如:

if (!IsPostBack) 
{ 
    ... add your code here 
} 
1

我猜你需要使用Page.IsPostBack

if (Page.IsPostBack) 
{ 
    // Do Something .. 
{ 
else 
{ 
    // Do something else .. 

}