2012-05-03 85 views
1

我完全沉迷於這一個,我是C#的全新,所以也許你們中的一個好人可以幫助我。我正在嘗試使用ADO.NET從表單域更新數據庫。試圖從TextBoxes插入數據庫到數據庫

基本上,我得到的錯誤是,我試圖插入空值到數據庫中。錯誤的確切文字是:

​​

這裏是後面的代碼,因爲我想使用的頁面:

private void ExecuteInsert(string firstName, string lastName, string emailAddress, string city, string phone) 
{ 
    SqlConnection conn = new SqlConnection(GetConnectionString()); 
    string sql = "INSERT INTO contactInfo (firstName, lastName, emailAddress, city, phone) VALUES " 
       + " (@firstName, @lastName, @emailAddress, @city, @phone)"; 

    try 
    { 
     conn.Open(); 
     SqlCommand cmd = new SqlCommand(sql, conn); 
     SqlParameter[] param = new SqlParameter[6]; 
     param[0] = new SqlParameter("@firstName", SqlDbType.NVarChar, 25); 
     param[1] = new SqlParameter("@lastName", SqlDbType.NVarChar, 25); 
     param[2] = new SqlParameter("@emailAddress", SqlDbType.NVarChar, 30); 
     param[3] = new SqlParameter("@city", SqlDbType.NVarChar, 50); 
     param[4] = new SqlParameter("@phone", SqlDbType.Int, 10); 

     param[0].Value = firstName; 
     param[1].Value = lastName; 
     param[2].Value = emailAddress; 
     param[3].Value = city; 
     param[4].Value = phone; 

     for (int i = 0; i < param.Length; i++) 
     { 
       cmd.Parameters.Add(param[i]); 
     } 

     cmd.CommandType = CommandType.Text; 
     cmd.ExecuteNonQuery(); 
    } 
    catch (System.Data.SqlClient.SqlException ex) 
    { 
     string msg = "Insert Error:"; 
     msg += ex.Message; 
     throw new Exception(msg); 
    } 
    finally 
    { 
     conn.Close(); 
    } 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    if (firstName.Text != null) 
    { 
     //call the method to execute insert to the database 
     ExecuteInsert(firstName.Text, 
         lastName.Text, 
         emailAddress.Text, 
         city.Text, 
         phone.Text); 
     Response.Write("Record was successfully added!"); 
     ClearControls(Page); 
    } 
    else 
    { 
     Response.Write("Please enter your name"); 
    } 
} 

public static void ClearControls(Control Parent) 
{ 

    if (Parent is TextBox) 
    { (Parent as TextBox).Text = string.Empty; } 
    else 
    { 
     foreach (Control c in Parent.Controls) 
      ClearControls(c); 
    } 
} 

如果有另一個我應該做的這樣,我會喜歡聽它。我似乎無法在網上找到好的信息。

+0

爲什麼你首先使用數組? – SLaks

回答

2

這條線:

SqlParameter[] param = new SqlParameter[6]; 

應爲(數組是太大了,你沒有設置最後一個參數):

SqlParameter[] param = new SqlParameter[5]; 
+0

+1,當'param [5]'爲NULL時,基本上,你將'param [5]'分配給集合。 – Tejs

+0

是的!非常感謝,這正是我一直在反覆研究這個項目的問題。我無法看到樹林,因爲我很習慣PHP。該代碼現在完美工作。 –

0

變化

SqlParameter[] param = new SqlParameter[6];

SqlParameter[] param = new SqlParameter[5];

您可以直接將參數添加到cmd.Parameters而不創建臨時陣列。