2011-07-07 36 views
0

我有幾個文本框的值將被插入到提交按鈕單擊的SQl表中。但它給了我「對象引用未設置爲對象的實例」異常。以下是我爲此編寫的代碼。請幫助我做到這一點。未將對象引用設置爲對象的實例ERROR

contact_new.aspx.cs

protected void btnSubmit_Click(object sender, EventArgs e) 
{ 
    DateTime dtime; 
    dtime = DateTime.Now; 
    string ocode = offercode.Text; 
    string firstname = firstnamepreapp.Text; 
    string lastname = lastnamepreapp.Text; 
    string email = emailpreapp.Text; 
    string phoneno = phonepreapp.Text; 
    string timetocall = besttimepreapp.SelectedItem.Value; 
    string time = dtime.ToString(); 

    //Insert the data into autoprequal table 

    <--- GIVES ME AN ERROR ON THIS LINE ---> 
    Insert.insertINTOautoprequal(ocode, time, firstname, lastname, email, phoneno, timetocall); 
} 

Insert.cs(App_Code文件類)

namespace InsertDataAccess 
{ 
public class Insert 
{ 
    public Insert() 
    { 
     // 
     // TODO: Add constructor logic here 
     // 
    } 
    public static bool insertINTOautoprequal(string code, string time, string first, string last, string email, string phoneno, string timetocall) 
    { 
     bool success = false; 
     SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connstring"].ConnectionString); 
     conn.Open(); 
     string query = "Insert INTO autoprequal(offercode, timeofday, firstname, lastname, emailID, phone, besttimetocall) Values(@offercode, @time, @first, @last, @email, @phoneno, @timetocall);"; 
     SqlCommand cmd = new SqlCommand(query, conn); 
     try 
     { 
      cmd.Parameters.AddWithValue("@offercode", code); 
      cmd.Parameters.AddWithValue("@time", time); 
      cmd.Parameters.AddWithValue("@first", first); 
      cmd.Parameters.AddWithValue("@last", last); 
      cmd.Parameters.AddWithValue("@email", email); 
      cmd.Parameters.AddWithValue("@phoneno", phoneno); 
      cmd.Parameters.AddWithValue("@timetocall", timetocall); 
      if (cmd.ExecuteNonQuery() == 1) success = true; 
      else success = false; 

      return success; 
     } 
     catch 
     { 
      throw; 
     } 
     finally 
     { 
      conn.Close(); 
     } 
    } 
} 

}通過代碼

+0

它總是會說這個或只是有時?這通常會在會話過期時發生。 –

+0

@Joe這是我第一次嘗試使用C#和SQL。所以我從來沒有通過這個例外。 – user787937

+0

調試它,並進入'insertINTOautoprequal'方法。這可能是錯誤所在。 –

回答

2

步驟,作爲誤差是最有可能從向上冒泡SQL插入例程。我猜想連接字符串沒有被從配置文件中提取出來,但是沒有經過這是一個瘋狂的猜測。我會花時間學習如何在Visual Studio中進行調試,因爲它可以幫助您輕鬆發現哪些問題無法解決,從而可以專注於可能存在的問題。

+0

我假設了同樣的事情。 –

+0

我也是 - 但我得到了-1。 :( –

+0

@ek_ny這是因爲你發表評論作爲一個問題 –

相關問題