Inserting DropDownList item into SQL Database - c#

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
}
}

Related

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.

How do I check if my pin exists in the SQL database while using asp.net?

I'm trying to check if the number I'm passing into the database already exists. I'm using a submit button on my form which submits my text box that has the id="pin" which contains the number I'm checking for. However, every time I submit it it says the number exists even when it doesn't. Any tips on what I'm doing wrong?
Here's my aspx.cs 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;
namespace Test
{
public partial class WebForm1 : System.Web.UI.Page
{
string connectionString = #"Data Source=DESKTOP-HOB2BSG\SQLEXPRESS;Initial Catalog=dogdata;Integrated Security=True";
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("RetrieveData", sqlCon);
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#pin", Int32.Parse(pin.Text.Trim()));
sqlCmd.ExecuteNonQuery();
// check if pin exists
using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) from dbo.tUser where pin = pin", sqlCon))
{
int userCount = (int)sqlCommand.ExecuteScalar();
if (userCount > 0)
{
Response.Write("<script>alert('Pin Exists!')</script>");
new SqlCommand("SELECT IMEI, Sim, DeviceNumber FROM dbo.tUser");
}
if (userCount < 1)
{
Response.Write("<script>alert('Pin Doesn't Exist')</script>");
}
}
}
}
}
}
Your logic is a little off, try:
protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT COUNT(*) from dbo.tUser where pin = #pin", sqlCon);
sqlCmd.CommandType = System.Data.CommandType.Text;
sqlCmd.Parameters.AddWithValue("#pin", Int32.Parse(pin.Text.Trim()));
var count = (int)sqlCmd.ExecuteScalar();
if (count > 0)
{
// Pin exists logic
}
if (count < 1)
{
// Pin doesn't exist logic
}
}
}

ConnectionString property has not been initialized IN ASP.NET

Please help me solving this problem:
The ConnectionString property has not been initialized.
I'm new to ASP.NET.
I'm trying to display the username after log in in e Label1.Text. But when I run the code, it shows this error... it also shows
INVALID OPERATION EXCEPTION WAS UNHANDLED
My code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Botswna_Centralized_Health_Card_System.healthcareOfficerLogins
{
public partial class healthcareOfficerLogins : System.Web.UI.Page
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["hospital_name"] == null)
{
Response.Redirect("~/hospital_login/hospital_login.aspx");
}
else
{
SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");
con.Open();
showdata();
}
}
public void showdata()
{
cmd.CommandText="select * from hospitallogins where hospital_Name='" + Session["hospital_Name"]+ "'";
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(ds);
Label1.Text= ds.Tables[0].Rows[0]["hospital_Name"].ToString();
}
}
}
You have 2 different instances of SqlConnection, both of them named con.
The first is declared in your class:
SqlConnection con = new SqlConnection();
The second is declared inside of Page_Load:
SqlConnection con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True");
When you call showdata(), you are using the first instance, which has not been initialized.
You really should refactor this to use a single connection. Also, to ensure you don't have any resource leaks, it is important to use a using block on SqlConnection or call Dispose in a finally block.
using (con = new SqlConnection("Data Source=BOW-PC\\BOW;Initial Catalog= BCHCS;Integrated Security=True"))
{
con.Open();
showdata();
}

Database connection string

I'm just trying create and write to the database file.
I don't know why connection string has turned such:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
With this connection string, I get this error:
Error CS1009 Unrecognized escape sequence
XXX_DATABASE_TEST D:\FOLDER\XXX_DATABASE_TEST\Form1.cs
So I've changed "/" to "\":
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:/Users/User/Documents/DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30
Error has gone, form loads, but database is empty, doesn't writes. Can you help me figure out, what I'm doing wrong here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace XXX_DATABASE_TEST
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\Documents\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
cmd = new SqlCommand("INSERT INTO testdata VALUES (Name, IDo, Gender) VALUES (#Name,#IDo,#Gender)", con);
cmd.Parameters.Add("#Name", textBox1.Text);
cmd.Parameters.Add("#IDo", textBox1.Text);
cmd.Parameters.Add("#Gender", comboBox1.SelectedItem.ToString());
cmd.ExecuteNonQuery();
}
}
}
I think your connection string have to be like this :
con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\User\\Documents\\DATA_TEST.mdf;Integrated Security=True;Connect Timeout=30");
And for localdb, you can do something like this too :
con = new SqlConnection("Data Source = .;Initial Catalog = DATA_TEST;Integrated Security = True")

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

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

Categories

Resources