the parameterized query error c# - c#

When i select an item from combo box(cb_oname) and enter the order then the program crashes and give error at executenonquery().i have highlighted below
Actually this code runs when i click the submit order button. the cb_ocat is the category of the item its data type is vnarchar(50)
string query = #"Insert into dbo.orders
(OrderType,OrderID,Product_Name, Product_category,Product_Quantity,
Product_Price,Date,Discount,Order_Price,Phone) values
(#txt_rdvalue,#txt_orderid,#cb_oname,#cb_ocat,#cb_oqty,
#txt_oprice,#Date,#txt_disc,#txt_orderprice,#txt_call)";
if (string.IsNullOrWhiteSpace(txt_rdvalue.Text) || string.IsNullOrWhiteSpace(txt_orderid.Text) || string.IsNullOrWhiteSpace(cb_oname.Text) || string.IsNullOrWhiteSpace(cb_ocat.Text) || string.IsNullOrWhiteSpace(cb_oqty.Text) || string.IsNullOrWhiteSpace(txt_oprice.Text) || string.IsNullOrWhiteSpace(txt_disc.Text))
{
lbl_incorrect.Visible = true;
}
else
{
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Pizza Mania;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.Parameters.Add(new SqlParameter("#Date", dateTimePicker1.Value.Date));
cmd.Parameters.AddWithValue("#txt_rdvalue", txt_rdvalue.Text);
cmd.Parameters.AddWithValue("#txt_orderid", Convert.ToDouble(txt_orderid.Text));
cmd.Parameters.AddWithValue("#cb_oname", cb_oname.SelectedItem);
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedItem);
cmd.Parameters.AddWithValue("#cb_oqty", Convert.ToDouble(cb_oqty.SelectedItem));
cmd.Parameters.AddWithValue("#txt_oprice", Convert.ToDouble((txt_oprice.Text)));
cmd.Parameters.AddWithValue("#txt_disc", Convert.ToDouble(txt_disc.Text));
cmd.Parameters.AddWithValue("#txt_orderprice", txt_orderprice.Text);
cmd.Parameters.AddWithValue("#txt_call", txt_call.Text);
if (txt_call.Text == null)
{
cmd.Parameters.AddWithValue(#"txt_call", txt_call.Text == null);
}
cmd.ExecuteNonQuery();// here i am getting the error that the parameterized query cb_' expects the parameter cb_ocat which was not supplied.
//MessageBox.Show("Order Inserted");
con.Close();
}

am not much sure of this but
if cb_oact is string try to convert it to String
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedItem.ToString());
Hope this works

Related

Value from DropDownList will not save into SQL Server table

I have a DropDownList that gets populated by a SQL Server table called tblVisa. My issue is that the values that are being populated from the SQL Server table are not being saved. Everything else gets saved except for my DropDownLists. I've tried using .SelectedValue and .Text, but it still does not work.
Here is my code
protected void PopulateVisaType()
{
List<ListItem> result = new List<ListItem> { new ListItem("", "") };
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "SELECT VisaType FROM tblVisa ORDER BY VisaType ASC" };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
result.Add(new ListItem(read["VisaType"].ToString(), read["VisaType"].ToString()));
}
read.Close();
sqlConn.Close();
cmd.Dispose();
DDLVisa.DataSource = result;
DDLVisa.DataValueField = "value";
DDLVisa.DataTextField = "text";
DDLVisa.DataBind();
}
Here's my code for saving the information into the database:
protected void LbSaveProfile_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "spSaveNewProviderInformation", CommandType = CommandType.StoredProcedure };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
cmd.Parameters.AddWithValue("#EmployeeNumber", TbEmployeeNumber.Text.Trim());
cmd.Parameters.AddWithValue("#SSN", TbSSN.Text.Trim());
cmd.Parameters.AddWithValue("#ContractType", DDLContractType.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Firstname", TbFirstname.Text.Trim());
cmd.Parameters.AddWithValue("#Lastname", TbLastname.Text.Trim());
cmd.Parameters.AddWithValue("#MiddleInitial", TbMiddleInitial.Text.Trim());
cmd.Parameters.AddWithValue("#ContractRenewalDate", TbContractRenewalDate.Text.Trim());
cmd.Parameters.AddWithValue("#Position", DDLPosition.Text.Trim());
cmd.Parameters.AddWithValue("#Specialty", DDLSpecialty.Text.Trim());
cmd.Parameters.AddWithValue("#PrimaryDepartment", DDLPrimaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#SecondaryDepartment", DDLSecondaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#Gender", DDLGender.Text.Trim());
cmd.Parameters.AddWithValue("#Birthdate", TbBirthdate.Text.Trim());
cmd.Parameters.AddWithValue("#EmailAddress", TbEmailAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PhoneNumber", TbPhoneNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Address", TbAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PassportNumber", TbPassportNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Citizenship", DDLCitizenship.Text.Trim());
cmd.Parameters.AddWithValue("#Visa", DDLVisa.Text.Trim());
cmd.Parameters.AddWithValue("#Status", 1);
cmd.ExecuteNonQuery();
sqlConn.Close();
Alert("Provider Information saved!");
ClearControls();
}
You much better to provide the drop down list with column names.
So, say this:
protected void PopulateVisaType()
{
SqlConnection sqlConn = new SqlConnection("");
using (SqlCommand cmd = new SqlCommand("SELECT VisaType FROM tblVisa ORDER BY VisaType ASC", sqlConn))
{
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
DDLVisa.DataSource = cmd.ExecuteReader();
DDLVisa.DataValueField = "VisaType";
DDLVisa.DataTextField = "VisaType";
DDLVisa.DataBind();
//DDLVisa.Items.Insert(0, new ListItem("")); // optional blank row choice
sqlConn.Close();
}
}
So the TextField, and the DataText field need to be a named column from the data source.
I also included an optional first blank option if you need/want/expect to have no choice.
However, keep in mind that this empty string should be translated into a null in your database if you don't allow (or want) empty strings, and want a null for that value. This applies to all of your values. (perhaps the stored procedure does this?).

SQL and C#: ExecuteNonQuery: Connection property has not been initialized [duplicate]

This question already has answers here:
ExecuteNonQuery: Connection property has not been initialized.
(7 answers)
Closed 3 years ago.
private void btnadd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source = INFINITY; Initial Catalog = Stock; Integrated Security = True"); // making connection
SqlCommand cmd;
int ud = 0;
//ud variable used in Updating and Deleting Record
if (txtprocode.Text != "" && txtproname.Text != "" && txtprotype.Text != "" && txtbrand.Text != "" && txtquantity.Text != "" && txtmeasurements.Text != "" && txtprice.Text != "")
{
cmd = new SqlCommand(#"INSERT INTO [dbo].[Product]([ProductCode],[ProductName],[ProductType],[Brand],[Quantity],[Measurements],[Price])
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)");
con.Open();
cmd.Parameters.AddWithValue("#ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("#ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("#ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("#Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("#Measurements", txtmeasurements.Text);
cmd.Parameters.AddWithValue("#Price", txtprice.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record inserted successfully");
//Reading data
SqlDataAdapter sda = new SqlDataAdapter();
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["ProductType"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["Brand"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["Quantity"].ToString();
dataGridView1.Rows[n].Cells[5].Value = item["Measurements"].ToString();
dataGridView1.Rows[n].Cells[6].Value = item["Price"].ToString();
}
}
else
{
MessageBox.Show("Please provide details!");
}
}
cmd.ExecuteNonQuery(); - this statement gets highlighted and error is shown:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: ExecuteNonQuery: Connection property has not been initialized.
Can anyone assist me with this? or tell me what changes to makes ?
Thank you :)
You need to set the Connection property of the SqlCommand object - or pass it as an argument to the SqlCommand constructor.
Also: please use the using (...) { ... } blocks - as illustrated here: SqlCommand.
You're creating the SqlConnection and the SqlCommand - but you're never connecting the two....
The command needs a connection - I'd recommend setting it when creating the command:
SqlCommand cmd = new SqlCommand("Your SQL query here", con);
You forgot to set the SqlCommand Connection property.
You can do cmd.Connection = con;
or
cmd = new SqlCommand(#"INSERT INTO [dbo].[Product]([ProductCode],[ProductName],[ProductType],[Brand],[Quantity],[Measurements],[Price])
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)", con);
Correct template is (Microsoft Docs):
private static void ExecuteNonQueryParameters(string connectionString, string queryString, Action<SqlCommmand> sqlCommandAction)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
sqlCommandAction();
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
}
Usage:
...
ExecuteNonQueryParameters(#"INSERT INTO
[dbo].[Product](
[ProductCode],
[ProductName],
[ProductType],
[Brand],
[Quantity],
[Measurements],
[Price])
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)",
cmd=>{
cmd.Parameters.AddWithValue("#ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("#ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("#ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("#Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("#Measurements", txtmeasurements.Text);
cmd.Parameters.AddWithValue("#Price", txtprice.Text);
});
...
Use:
string CS = ConfigurationManager.ConnectionString["<ConnectionString located in web.config file or Create it in web.config file>"].connectionString;
using(SqlConnection con = new SqlConnection(CS))
{
con.Open();
query = "INSERT INTO Product(ProductCode, ProductName, ProductType, Brand, Quantity, Measurements, Price)
VALUES(#ProductCode,#ProductName,#ProductType,#Brand,#Quantity,#Meter,#Price)";
using(SqlCommand cmd = new SqlCommand(query,con))
{
cmd.Parameters.AddWithValue("#ProductCode", txtprocode.Text);
cmd.Parameters.AddWithValue("#ProductName", txtproname.Text);
cmd.Parameters.AddWithValue("#ProductType", txtprotype.Text);
cmd.Parameters.AddWithValue("#Brand", txtbrand.Text);
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text);
cmd.Parameters.AddWithValue("#Meter", txtmeasurements.Text);
cmd.Parameters.AddWithValue("#Price", txtprice.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
By the way you error was in #Meter and #Measurements
In SQL query you write it #Meter and in
cmd.Parameters.AddWithValue("#Measurements");

It says this is "DB_Student.TBLStudent" is an invalid object. Why is that?

I'm getting data from another database the first connection is from con and the second database is DB_Student. I want to get the signature from DB_Student and put it into DB_Attendance which is con.
SqlCommand cmd = new SqlCommand();
cmd = con.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
con.Open();
cmd.CommandType = CommandType.Text;
string Query = "INSERT INTO TBL_Attendance(Signature) SELECT
Signature FROM DB_Students.TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "'";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Please Delete the row without name.");
}

Incorrect syntax near 'achternaam'

I am trying to insert a new row into a SQL Server table from a Winforms application. As far as I know my query is correct but Visual Studio keeps returning an error:
Incorrect syntax near 'achternaam'
I hope that someone can point me in the right direction.
public void UpdateGegevens(int id, string voornaam, string achternaam, string functie, DateTime geboortedatum, decimal uurloon)
{
if (ReturnFirstTime(id) == true)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO tbl_Gegevens (Id, voornaam, achternaam, geboortedatum, functie, uurloon) VALUES (#Id, #vn, #an, #gb, #f, #ul);";
command.Parameters.Add("#Id", SqlDbType.Int).Value = id;
command.Parameters.Add("#vn", SqlDbType.VarChar).Value = voornaam;
command.Parameters.Add("#an", SqlDbType.VarChar).Value = achternaam;
command.Parameters.Add("#f", SqlDbType.VarChar).Value = functie;
command.Parameters.Add("#gb", SqlDbType.Date).Value = geboortedatum;
command.Parameters.Add("#ul", SqlDbType.Money).Value = uurloon;
try
{
con.Open();
command.ExecuteScalar();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
else
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = con;
command.CommandType = CommandType.Text;
command.CommandText = "UPDATE tbl_Gegevens SET voornaam=#vn achternaam=#an geboortedatum=#gb funtie=#f uurloon=#ul WHERE Id = #Id;";
command.Parameters.AddWithValue("#Id", id);
command.Parameters.AddWithValue("#vn", voornaam);
command.Parameters.AddWithValue("#an", achternaam);
command.Parameters.AddWithValue("#gb", geboortedatum);
command.Parameters.AddWithValue("#f", functie);
command.Parameters.AddWithValue("#ul", uurloon);
try
{
con.Open();
command.ExecuteNonQuery();
}
catch (SqlException ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
}
}
}
Here is a specification of tbl_Gegevens:
create table [dbo].[tbl_Gegevens] (
[Id] int not null
, [voornaam] nvarchar(50) null
, [achternaam] nvarchar(50) null
, [geboortedatum] date null
, [functie] nvarchar(50) null
, [uurloon] smallmoney null
, primary key clustered ([Id] asc)
);
I think my dbms is ADO.Net.
This is the way i'm passing the info to the method:
private void btnConfirm_Click(object sender, EventArgs e)
{
if (tbName.Text != "" && tbSurname.Text != "" && tbFunction.Text
!= "" && dtpBirthdate.Value != date && nudSalary.Value != 0)
{
Database1.SetFirstTime(ID);
Database1.UpdateGegevens(ID, tbName.Text, tbSurname.Text, tbFunction.Text, dtpBirthdate.Value, nudSalary.Value);
this.Hide();
frmMain fm = new frmMain(ID);
fm.Show();
}
else
{
MessageBox.Show("Vul alle velden in!");
}
}
This is the query i use to get my id:
public int ReturnLoginID(string username, string password)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from tbl_Login where UserName=#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", username);
cmd.Parameters.AddWithValue("#password", password);
int ID = 9999;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
ID = reader.GetInt32(0);
}
con.Close();
return ID;
}
In the UPDATE part of your code there are no commas to separate the fields in the SET list
command.CommandText = #"UPDATE tbl_Gegevens SET voornaam=#vn,
achternaam=#an, geboortedatum=#gb,
funtie=#f, uurloon=#ul WHERE Id = #Id;";
I think that this question could be used to underline the importance of using a debugger. This problem would be solved much sooner if you had stepped through your code using the debugger.

Error in ExecuteNonQuery()

I am getting continuously an error on ExecuteNonQuery();. I have tried many ways but don't know where I am wrong.
I am using float data type in orderid, price, quantity, discount, order price columns in SQL Server.
Kindly help.
string query = "Insert into dbo.orders (OrderType,Product_Name,Product_Category,Product_Quantity,Product_Price,Date,Discount) values(#txt_rdvalue,#cb_oname,#cb_ocat,#cb_oqty,#txt_oprice,#Date,#txt_disc)";
if (string.IsNullOrWhiteSpace(txt_rdvalue.Text) || string.IsNullOrWhiteSpace(cb_oname.Text) || string.IsNullOrWhiteSpace(cb_ocat.Text) || string.IsNullOrWhiteSpace(cb_oqty.Text))
{
lbl_incorrect.Text = "please fill up all the fields";
lbl_incorrect.Visible = true;
}
else
{
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=Pizza Mania;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.Parameters.AddWithValue("#txt_rdvalue",txt_rdvalue.Text);
cmd.Parameters.AddWithValue("#txt_orderid",txt_orderid.Text);
cmd.Parameters.AddWithValue("#cb_oname", cb_oname.SelectedText);
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedText);
cmd.Parameters.AddWithValue("#cb_oqty", cb_oqty.SelectedValue);
cmd.Parameters.AddWithValue("#txt_oprice", (txt_oprice.Text));
cmd.Parameters.AddWithValue("#txt_disc", txt_rdvalue.Text);
cmd.Parameters.Add(new SqlParameter("#Date", dateTimePicker1.Value.Date));
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted");
}
}
}
The error message I am getting:
The parameterized query '(#txt_rdvalue nvarchar(8),#txt_orderid
int,#cb_oname nvarchar(40' expects the parameter '#cb_oqty', which was
not supplied
yes i have done it. The convert to double thing works
thankyou all
Appriciated.[enter link description here][1]
cmd.Parameters.AddWithValue("#txt_rdvalue",txt_rdvalue.Text);
cmd.Parameters.AddWithValue("#txt_orderid",Convert.ToDouble(txt_orderid.Text));
cmd.Parameters.AddWithValue("#cb_oname", cb_oname.SelectedText);
cmd.Parameters.AddWithValue("#cb_ocat", cb_ocat.SelectedText);
cmd.Parameters.AddWithValue("#cb_oqty", Convert.ToDouble(cb_oqty.SelectedValue));
cmd.Parameters.AddWithValue("#txt_oprice",Convert.ToDouble((txt_oprice.Text)));
cmd.Parameters.AddWithValue("#txt_disc",Convert.ToDouble(txt_disc.Text));
cmd.Parameters.Add(new SqlParameter("#Date", dateTimePicker1.Value.Date));
[1]: http://www.stackoverflow.com/alygorejaanswers
You are providing #txt_orderid(cmd.Parameters.AddWithValue("#txt_orderid",txt_orderid.Text);) parameter which doesn't exists.Check your code once again.
If it's autoincrement coloumn why are you providing this.
Also datatype mismatching is happening.

Categories

Resources