how to insert data into sql server in asp.net website? - c#

I tried to insert data into sql server from my website build in vs 2008.For that I used button click event .I tried code shown in youtube but the code doesn't work .It shows error in my website.
The code in .aspx.cs file is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
conn.Open();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into Insert values('"+txtCity.Text+"','"+txtFName.Text+"','"+txtLName.Text+"')",conn);
cmd.ExecuteNonQuery();
conn.Close();
Label1.Visible =true;
Label1.Text = "Your data inserted successfully";
txtCity.Text = "";
txtFName.Text = "";
txtLName.Text = "";
}
}
`

Okay, let's fix this code up just a little. You're getting there:
var cnnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var cmd = "insert into Insert values(#City,#FName,#LName)";
using (SqlConnection cnn = new SqlConnection(cnnString))
{
using (SqlCommand cmd = new SqlCommand(cmd, cnn))
{
cmd.Parameters.AddWithValue("#City",txtCity.Text);
cmd.Parameters.AddWithValue("#FName",txtFName.Text);
cmd.Parameters.AddWithValue("#LName",txtLName.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
A couple things to note about the modified code.
It's leveraging the using statement to ensure that resources are properly disposed.
It's parameterized to ensure that SQL Injection isn't a possibility.
It's not storing a connection object anywhere, get rid of that stored connection.

**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=mrinmoynandy;User ID=**;Password=****");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SumbitBtn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into streg(Name,Father,Mother,Dob,Sex,Category,Maritial,Vill,Po,Ps,Dist,State,Pin,Country) values (#name,#father,#mother,#dob,#sex,#category,#maritial,#vill,#po,#ps,#dist,#state,#pin,#country)", con);
cmd.Parameters.AddWithValue(#"name", StNumTxt.Text);
cmd.Parameters.AddWithValue(#"father", FatNumTxt.Text);
cmd.Parameters.AddWithValue(#"mother", MotNumTxt.Text);
cmd.Parameters.AddWithValue(#"dob", DobRdp.SelectedDate);
cmd.Parameters.AddWithValue(#"sex", SexDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"category", CategoryDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"maritial", MaritialRbl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"vill", VillTxt.Text);
cmd.Parameters.AddWithValue(#"po", PoTxt.Text);
cmd.Parameters.AddWithValue(#"ps", PsTxt.Text);
cmd.Parameters.AddWithValue(#"dist", DistDdl.SelectedItem.Text);
cmd.Parameters.AddWithValue(#"state", StateTxt.Text);
cmd.Parameters.AddWithValue(#"pin", PinTxt.Text);
cmd.Parameters.AddWithValue(#"country", CountryTxt.Text);
con.Open();
con.Close();
}
}
Thanks
Mrinmoy Nandy
Phone No.: +91 9800451398
**

Creating procedure will avoid sql injection.
SQL
Create procedure insert
(#City,#FirstName,#LastName)
{
insert into tablename (City,FName,LName)
values(#City,#FirstName,#LastName)
}
C#
SqlConnection con=new sqlconnection("give ur connection string here");
sqlcommand cmd=new sqlcommand();
con.open();
cmd=new sqlcommand("insert",con);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.addwithvalue("#City",txtCity.text);
cmd.parameters.addwithvalue("#FName",txtFName.text);
cmd.parameters.addwithvalue("#LNAme",txtLName.text);
cmd.ExecuteNonQuery();
con.close();

Related

Inserting DropDownList item into SQL Database

I have a DropDownList which is populated with data from an SQL Table. Within the webform when users select an item from that list, i want it to insert the selected choice into another SQL table, everything works other than the DropDownLists
I've tried :
cmd.Parameters.AddWithValue("#*", ddl*.SelectedValue);
cmd.Parameters.AddWithValue("#*", ddl*.SelectedItem.Text);
etc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Data;
using System.Configuration;
using System.Text;
using System.Drawing;
namespace VXUK2
{
public partial class booking_system : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// SQL Query For DropDownList1 (CIT Company)
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\****;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("Select CIT_ID, CIT_CompanyName from CIT_Details", con);
ddlCITCompany.DataSource = cmd.ExecuteReader();
ddlCITCompany.DataTextField = "CIT_CompanyName";
ddlCITCompany.DataValueField = "CIT_ID";
ddlCITCompany.DataBind();
// SQL Query for DropDownList2 (Site Details)
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con2.Open();
SqlCommand cmd2 = new SqlCommand("Select Site_ID, Site_Name from Site_Details", con2);
ddlVisitingCentre.DataSource = cmd2.ExecuteReader();
ddlVisitingCentre.DataTextField = "Site_Name";
ddlVisitingCentre.DataValueField = "Site_ID";
ddlVisitingCentre.DataBind();
}
protected void Submit2_Click(object sender, EventArgs e)
{
//LocalDB Connection & Execution String
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\***;Persist Security Info=True;User ID=***;Password=****;Connect Timeout=30");
con.Open();
String st = "INSERT INTO Booking_Data (Visiting_Centre, Expected_Arrival_Date, Expected_Arrival_Time, Actual_Arrival_Date, Actual_Arrival_Time, CIT_Company, Driver_Name, Vehicle_Registration, Supplied_Password, Delivery_In, Delivery_Out, Time_Booked_In, Time_Booked_Out) values (#Visiting_Centre, #Expected_Arrival_Date, #Expected_Arrival_Time, #Actual_Arrival_Date, #Actual_Arrival_Time, #CIT_Company, #Driver_Name, #Vehicle_Registration, #Supplied_Password, #Delivery_In, #Delivery_Out, #Time_Booked_In, #Time_Booked_Out)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Visiting_Centre", ddlVisitingCentre.SelectedValue);
cmd.Parameters.AddWithValue("#Expected_Arrival_Date", txtExpectedArrivalDate.Text);
cmd.Parameters.AddWithValue("#Expected_Arrival_Time", txtExpectedArrivalTime.Text);
cmd.Parameters.AddWithValue("#Actual_Arrival_Date", txtActualArrivalDate.Text);
cmd.Parameters.AddWithValue("#Actual_Arrival_Time", txtActualArrivalTime.Text);
cmd.Parameters.AddWithValue("#CIT_Company", ddlCITCompany.SelectedValue);
cmd.Parameters.AddWithValue("#Driver_Name", txtDriverName.Text);
cmd.Parameters.AddWithValue("#Vehicle_Registration", txtVehicleRegistration.Text);
cmd.Parameters.AddWithValue("#Supplied_Password", txtSuppliedPassword.Text);
cmd.Parameters.AddWithValue("#Delivery_In", txtDeliveryIn.Text);
cmd.Parameters.AddWithValue("#Delivery_Out", txtDeliveryOut.Text);
cmd.Parameters.AddWithValue("#Time_Booked_In", txtTimeBookedIn.Text);
cmd.Parameters.AddWithValue("#Time_Booked_Out", txtTimeBookedOut.Text);
cmd.ExecuteNonQuery();
con.Close();
You have to add not isPostBack as every time any function called it reloads the Entire web-page, So every time you can see the first data is selected.
By Adding !IsPostBack the Page will not Re-Load Data Implicitly.
This can Solve your Problem in Selecting Data.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Your Code
}
}

How to add passed value to database?

I'm practicing on WebApplication in ASP.NET C#
I have created Product Page in that page I have created gridview with data coming from the database also there is the button called Edit in each row. It will take you to Update Page with that row data. and it will put the values in textbox accordingly.
There are text fields and drop box in Update page, but when i make change to data and click on update button, the data doesn't update in database.
Product.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5.Product
{
public partial class Product1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string pid = GridView1.SelectedRow.Cells[0].Text;
Response.Redirect("UpdateProduct.aspx?Product_ID=" + pid);
}
}
}
UpdateProduct.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
namespace WebApplication5.Product
{
public partial class UpdateProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
String myquery = "Select * from Product where pro_id=" + Request.QueryString["Product_ID"];
SqlConnection con = new SqlConnection(mycon);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = myquery;
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtpid.Text = ds.Tables[0].Rows[0]["pro_id"].ToString();
txtpname.Text = ds.Tables[0].Rows[0]["pro_name"].ToString();
txtpprice.Text = ds.Tables[0].Rows[0]["pro_price"].ToString();
txtpq.Text = ds.Tables[0].Rows[0]["pro_qty"].ToString();
}
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con1.Open();
string sql ="UPDATE Product set pro_name='"+txtpname.Text.ToString()+"',cat_name='"+DropDownList1.SelectedValue.ToString()+"',pro_price='"+txtpprice.ToString()+"',pro_qty='"+txtpq.ToString()+"'where pro_id='"+txtpid.Text.ToString()+"'";
SqlCommand cmd1 = new SqlCommand(sql,con1);
cmd1.ExecuteNonQuery();
Response.Write("Updated!");
}
}
}
Please make try catch block with SQLcatch(SqlException ex), and try to use property's. Also you have nice tool in MSSQL, it's called "SQL server profiler".
Check this : pro_qty='"+txtpq.ToString()+"'--give me space---where pro_id
You don't have space between filed and where clause, give one space after pro_qty and where, your query dosen't execute and you don't see error output, because you don't use all tools.

Connected database not updating

I have connected my SQL database to my aspx.net form but when I entered the details in the form, it does not seem to update in my SQL Table. I've checked the codes and there doesn't seem to be any errors. Could anyone see what's wrong with my code?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.Sql;
public partial class CustomerLogin : System.Web.UI.Page {
public string sqlTest = "Data Source=TEAFAMILY;Initial Catalog=Bolsen;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e) {
}
static readonly string scriptSuccessNewAccount =
"<script language=\"javascript\">\n" +
"alert (\"Your account has been succesfully created - Thank You!\");\n" +
"</script>";
protected void Button1_Click1(object sender, EventArgs e) {
SqlConnection mDB = new SqlConnection(sqlTest);
mDB.Open();
Type csType = this.GetType();
SqlCommand cmd;
SqlDataReader rdr;
string strSQLSelect = "SELECT cEmail FROM Customers ORDER BY cEmail";
cmd = new SqlCommand(strSQLSelect, mDB);
Console.Write(cmd);
rdr = cmd.ExecuteReader();
//insert new record
string strSQLInsert = "INSERT INTO"
+ " Customers (cFirstname, cLastname, cNumber, cCompanyname, cAdd, cEmail, cPassword)"
+ " VALUES (#FN, #LN, #Num, #Cname, #Add, #Email, #Pw)";
cmd = new SqlCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#FN", txtFN.Text);
cmd.Parameters.AddWithValue("#LN", txtLN.Text);
cmd.Parameters.AddWithValue("#Num", txtPN.Text);
cmd.Parameters.AddWithValue("#Cname", txtComp.Text);
cmd.Parameters.AddWithValue("#Add", txtCompAdd.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Pw", txtPW.Text);
cmd.ExecuteNonQuery();
mDB.Close();
ClientScript.RegisterStartupScript(csType, "Success", scriptSuccessNewAccount);
}
}
You are not closing your SqlDataReader. Asides from not calling rdr.Read() and getting any values, you need to call rdr.Close() before executing your second sql statement.
Per MSDN - While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.

Input data from browser is not stored in table

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DELL\Documents\reg.mdf;Integra
ted Security=True;Connect Timeout=90");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into signup values" + "
(#id,#name)", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
}
}
I used the above code. It has no errors but it doesn't save data in the table when I click on submit button. I'm using visual studio 2015 C# and storing data in localhost. Please help.
You need to call ExecuteNonQuery
con.Open();
SqlCommand cmd = new SqlCommand("insert into signup values" + "(#id,#name)", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
cmd.ExecuteNonQuery();
Step-1
insert code in cs file
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conectionStr"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_insert_signup", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#id", SqlDbType.Int)).Value = Convert.ToInt32(TextBox1.Text);
cmd.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar, 50)).Value = TextBox2.Text;
conn.Open();
try
{
int isSave = cmd.ExecuteNonQuery();
if (isSave > 0)
{
Response.Write("data save successfully");
}
else
{
Response.Write("data save operation failed");
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
conn.Close();
cmd.Dispose();
}
}

C# insert data into database windows form app

I need to build a application where people can make a reservation but before doing that they need to fill in some information. I get this error code at the moment when i try to save the data: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BonTemps
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var Form1 = new Form1();
Form1.Show();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Home_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bonTempsDBDataSet.Tafel' table. You can move, or remove it, as needed.
this.tafelTableAdapter.Fill(this.bonTempsDBDataSet.Tafel);
}
private void btnOpslaan_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = (#"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres), VALUES ('" + txtNaam.Text + "','" + txtAdres.Text + "','" + txtWoon.Text + "','" + txtTel.Text + "','" + txtMail.Text + "'");
com.ExecuteNonQuery();
sc.Close();
}
}
}
Remove the comma Before VALUES.
If that is not enough, you can debug and copy the generated string from Command Text and try running it directly in SQL Server Mangement Studio or similar
A typographical error remove the COMMA before the word VALUES.
You have to pass an open SqlConnection to your SqlCommand to make it work:
com.Connection = sc;
Also, consider using named parameters to pass data to your query to make your query more error-proof:
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = #"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres) VALUES (#naam, #adres, #woon, #tel, #mail)";
com.Parameters.AddWithValue("#naam", txtNaam.Text);
com.Parameters.AddWithValue("#adres", txtAdres.Text);
com.Parameters.AddWithValue("#woon", txtWoon.Text);
com.Parameters.AddWithValue("#tel", txtTel.Text);
com.Parameters.AddWithValue("#mail", txtMail.Text);
com.ExecuteNonQuery();
sc.Close();
using (var sc = new SqlConnection("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True"))
{
using (var com = new SqlCommand("sql cmd text", sc))
{
try
{
sc.Open();
com.ExecuteNonQuery();
}
catch
{
}
}
}

Categories

Resources