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!");
}
}
}
No comments:
Post a Comment