简体   繁体   中英

ASP.NET inserting form data into database

I'm pretty new to ASP.NET but I have a form with textboxes, some of which are required using the RequiredFieldValidator. And once everything has been filled out I want to insert into my database. I'm reading about all different ways to indest and not sure the best, most current way of doing an insert. Here's what I have but keep getting the error:

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 50: finally Line 51: { Line 52: conn.Close(); Line 53: } Line 54: }

C# code -- the only thing I'm trying to insert is textbox with ID=BookingName

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.IO;
using System.Net.Mail;
using System.Data.SqlClient;

public partial class _Default : BasePage
{


     protected void Page_Load(object sender, EventArgs e)
        {
           // BookingName.Text = "test";
        }

private void ExecuteInsert(string name)
{
    string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
    SqlConnection conn = null;
    string sql = "INSERT INTO tbBooking (BookingName) VALUES "
                + " (@BookingName)";

    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlParameter[] param = new SqlParameter[1];
        //param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
        param[0] = new SqlParameter("@BookingName", System.Data.SqlDbType.VarChar, 50);

        param[0].Value = name;

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

        cmd.CommandType = System.Data.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 BtnCatering_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {

        //call the method to execute insert to the database
        ExecuteInsert(BookingName.Text);
        Response.Write("Record was successfully added!");
    }
}
}

You're not actually assigning conn so it never has a value.

conn = new SqlConnection(connString);

For an even better solution wrap the assignment in a using statement. See here http://www.dotnetperls.com/sqlconnection

From your code you have not created a new instance of the SqlConnection

SqlConnection conn = null;

Change this to;

SqlConnection conn = new SqlConnection(connString);

Or to make sure you catch any errors when creating the new SqlConnection, add

conn = new SqlConnection(connString)

Into your try catch statement just before you open the connection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM