Hi Morning all,
here I've code how to insert data into multiple tables in Sql Server using asp.net C# form but the data unable to enter ang got error, may anyone help fix it form me? because i've tried so many times already but still cannot, there is the code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class Customer : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsPostBack) // form submitted
{
SqlConnection sc = null;
SqlCommand cmd = null;
try
{
sc = new SqlConnection(ConfigurationManager.ConnectionStrings["CompMSConnectionString1"].ConnectionString);
//sc = new SqlConnection(@"Data Source=suliya-pc;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\CompMS.mdf";Integrated Security=True;User Instance=True");
sc.Open();
string query1 = String.Format(@"Insert Into Customer (Customer_Id, NRIC, First_Name, Last_Name, Company_Name, Phone_No, Fax_No, Email) "
+ " VALUES (@Customer_Id, @NRIC, @First_Name, @Last_Name, @Company_Name, @Phone_No, @Fax_No, @Email)");
//cmd.CommandType = CommandType.Text;
//cmd.Parameters.AddWithValue("@Customer_Id", Customer_Id.Text);
cmd.Parameters.AddWithValue("@NRIC", IC.Text);
cmd.Parameters.AddWithValue("@First_Name", FName.Text);
cmd.Parameters.AddWithValue("@Last_Name", LName.Text);
cmd.Parameters.AddWithValue("@Company_Name", CName.Text);
cmd.Parameters.AddWithValue("@Phone_No", PhoneNo.Text);
cmd.Parameters.AddWithValue("@Fax_No", FaxNo.Text);
cmd.Parameters.AddWithValue("@Email", Email.Text);
cmd = new SqlCommand(query1, sc);
cmd.ExecuteNonQuery();
sc.Close();
string query2 = String.Format(@"Insert Into Customer_Address [CODE][/CODE](Address_Line1, Address_Line2, City, State_Province, Postal_Code, Country) "
+ " VALUES (@Address_Line1, @Address_Line2, @City, @State_Province, @Postal_Code, @Country)");
cmd.Parameters.AddWithValue("@Address_Line1", AddressLine1.Text);
cmd.Parameters.AddWithValue("@Address_Line2", AddressLine2.Text);
cmd.Parameters.AddWithValue("@City", City.Text);
cmd.Parameters.AddWithValue("@State_Province", State.Text);
cmd.Parameters.AddWithValue("@Postal_Code", Postcode.Text);
cmd.Parameters.AddWithValue("@Country", Country.Text);
cmd = new SqlCommand(query2, sc);
cmd.ExecuteNonQuery();
}
finally // clean up
{
if(cmd != null)
cmd.Dispose();
if(sc != null)
sc.Close();
}
}
}
}