user787937
user787937

Reputation: 61

Object reference not set to an instance of an object ERROR

I have few textboxes whose values are to be inserted into SQl table on Submit button click. But it gives me "Object reference not set to an instance of an object" Exception. Below is the code I have written for this. Please do help me in this.

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 class)

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();
        }
    }
}

}

Upvotes: 0

Views: 468

Answers (1)

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

Step through the code, as the error is most likely bubbling up from the SQL insert routine. I woulud guess the connection string is not being pulled from the configuration file, but without stepping through that is a wild guess. I would take time to learn how to debug in Visual Studio, as it will help you easily spot what cannot be a problem so you can focus on what is likely to be the problem.

Upvotes: 2

Related Questions