2015-10-06 118 views
0

此代碼在sql命令繼承時應該帶我到頁面,失敗時會顯示錯誤頁面。每當我通過表單插入值,它都會將我帶到錯誤頁面。不知何故,我的物品沒有被插入。幫助將不勝感激嘗試通過c#將數據插入到數據庫的表中#/ asp.net

public partial class StudentManage : System.Web.UI.Page 
{ 
    protected void Add_Click(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString); 
     con.Open(); 

     // here added "@" to write continuous strind in new line 
     SqlCommand cmd = new SqlCommand(@"INSERT INTO ManageStudents(StudentName, StudentEmail, StudentAddress, StudentCity) VALUES(@name, @email, @address, @city)",con); 
     cmd.Parameters.AddWithValue("@name", txtStudentName.Text); 
     cmd.Parameters.AddWithValue("@email", txtStudentEmail.Text); 
     cmd.Parameters.AddWithValue("@address", txtStudentAddress.Text); 
     cmd.Parameters.AddWithValue("@city", txtStudentCity.Text); 

     SqlDataAdapter da1 = new SqlDataAdapter(cmd); 
     DataTable dt2 = new DataTable(); 
     da1.Fill(dt2); 

     if (dt2.Rows.Count > 0) 
     { 
      Response.Write("Table Updated"); 
      Response.Redirect("StudentManage.aspx"); 
     } 
     else 
     { 
      Response.Redirect("Error.aspx"); 
      //ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>"); 
     } 
    } 
} 

回答

3

要執行INSERT,UPDATE或DELETE您需要使用ExecuteNonQuery()方法,而不是一個DataTable的語句。

var result = cmd.ExeuteNonQuery(); 
if(result > 0) 
{ 
    Response.Write("Table Updated"); 
    Response.Redirect("StudentManage.aspx"); 
} 
// ... 
+0

這是爲什麼壽? –

+0

它感謝一羣夥伴。 –

0

我想這是一個測試項目,因爲你的代碼有三個主要問題,

  • 您應該創建一個使用或嘗試最後關閉連接
  • 把與呼叫數據到同一層的用戶界面它不是一個好的練習 的做法。
  • 上次填充只做一個選擇,不更新表格。使用command.ExecuteNotQuery代替

我希望這可以幫助您

相關問題