我有几个文本框,其值将在“提交”按钮单击时插入到SQl表中。但它给了我“对象引用未设置为对象的实例”异常。以下是我为此编写的代码。请帮帮我。
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 :(得分:2)
逐步执行代码,因为错误很可能是从SQL插入例程中冒出来的。我猜想连接字符串没有从配置文件中提取出来,但没有单步执行这是一个疯狂的猜测。我会花时间学习如何在Visual Studio中进行调试,因为它可以帮助您轻松发现不存在问题的内容,因此您可以专注于可能出现的问题。