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");
Related
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?).
New to C# and working on a Windows Form application. I am attempting to execute an update query against a SQL database, but keep running into "Must declare the scalar variable" error and I do not understand why.
The below code successfully opens the connection. My update statement is valid. Looking through a lot of posts on this topic and I am just not seeing my error... any help would be appreciated.
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//below AddWithValue gives error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#stationId".'
//command.Parameters.AddWithValue("#stationId", 1);
//command.Parameters.AddWithValue("#jobId", JobId);
//next I tried this, and the same error:
//System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#stationId".'
command.Parameters.Add("#stationId", SqlDbType.Int);
command.Parameters["#stationId"].Value = 1;
command.Parameters.Add("#jobId", SqlDbType.Int);
command.Parameters["#jobId"].Value = JobId;
adapter.UpdateCommand = new SqlCommand(strSql, conn);
adapter.UpdateCommand.ExecuteNonQuery();
}
}
I have checked your code and it's required some changes. Please try to run below code:
public void SetJobStatus(int JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
try
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
SqlCommand command = new SqlCommand(strSql, conn);
command.CommandType = CommandType.Text;
command.Parameters.Add("#stationId", SqlDbType.Int);
command.Parameters["#stationId"].Value = 1;
command.Parameters.Add("#jobId", SqlDbType.Int);
command.Parameters["#jobId"].Value = JobId;
command.ExecuteNonQuery();
}
catch (Exception ex)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
Tips:
Always close connection after completion of task or in case of error.
Thanks to everyone who chimed in here. WSC's comment did the trick- changing adapter.UpdateCommand = command; worked. I tried three variations of adding parameters after making WSC's change- two of them worked, one did not.
My revised code is below. I have all three variations listed in the code- hopefully this will help somebody else out.
public void SetJobStatus(long JobId)
{
string strSql = "update Jobmaster set jobstatus = 5 where equid = #stationId AND ID <> #jobId AND OfflineEntry = 0;";
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = GlobalVars.connString;
conn.Open();
// use the connection here, and check to confirm it is open
if (conn.State != ConnectionState.Open)
{
if (conn != null)
{
conn.Close();
}
conn.Open();
}
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
command = new SqlCommand(strSql, conn);
//works
command.Parameters.AddWithValue("#stationId", GlobalVars.stationId);
command.Parameters.AddWithValue("#jobId", JobId);
//works
//command.Parameters.Add("#stationId", SqlDbType.Int);
//command.Parameters["#stationId"].Value = 5;
//command.Parameters.Add("#jobId", SqlDbType.Int);
//command.Parameters["#jobId"].Value = JobId;
//throws error at adapter.UpdateCommand.ExecuteNonQuery line:
//'The parameterized query '(#stationId int,#jobId int)update Jobmaster set jobstatus = 5 wh' expects the parameter '#stationId', which was not supplied.'
//command.Parameters.Add("#stationId", SqlDbType.Int, 5);
//command.Parameters.Add("#jobId", SqlDbType.Int, (int)JobId);
adapter.UpdateCommand = command;
adapter.UpdateCommand.ExecuteNonQuery();
}
}
When executing this query with parameters added as values, i get an error saying my syntax is wrong. I tried following multiple tutorials, looking up questions here is stack overflow, and when comparing, they seem the same, but mine does not seem to work.
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =C:\\Users\\fidyc\\OneDrive\\Desktop\\ProgrII.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT Product_Orders(order_ID,plankCount,thickness,width,height)VALUES(#order_ID, #plankCount, #thickness, #width, #height)");
cmd.Parameters.Add("#order_ID", OleDbType.Integer).Value = orderID;
cmd.Parameters.Add("#plankCount", OleDbType.Decimal).Value = plankCount;
cmd.Parameters.Add("#thickness", OleDbType.Decimal).Value = thickness;
cmd.Parameters.Add("#width", OleDbType.Decimal).Value = width;
cmd.Parameters.Add("#height", OleDbType.Decimal).Value = height;
cmd.Connection = con;
con.Open();
if (con.State == ConnectionState.Open)
{
/*try
{*/
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
con.Close();
/*}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
con.Close();
}*/
}
Edit: values are passed to the function
public static void Push(int orderID, decimal plankCount, decimal thickness, decimal width, decimal height)
{
The problem turned out to be the count column name, as sql has a count command, it needs to be
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,[count],thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
instead of
OleDbCommand cmd = new OleDbCommand("INSERT INTO Product_Orders(order_ID,count,thickness,width,height)VALUES(#order_ID, #count, #thickness, #width, #height)");
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"INSERT INTO bookRated "+
"([firstName], [lastName]) "+
"VALUES(#firstName, #lastName)";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#firstName", firstName),
new OleDbParameter("#lastName", lastName),
});
cmd.ExecuteNonQuery();
}
I want to show data from my database in dataGridView after saved new record. After I clicked button, the data saved, but not show in datagridview. How can I show that data?
private void btn_add_Click(object sender, EventArgs e)
{
{
if (textBox_tarikh.Text == "" || textBox_resit.Text == "" || textBox_bayaran.Text == "")
{
MessageBox.Show("Please Fill In The Blank");
}
else
{
String bResult = textBox_ic.Text;
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"; // add your conncetion string here
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT Pembayaran (Description, Date, No_Resit, Payment, Studentic) VALUES (#Description, #date, #resit, #payment, #val)", connection);
cmd.Parameters.AddWithValue("#val", bResult);
cmd.Parameters.AddWithValue("#Description", label4.Text);
cmd.Parameters.AddWithValue("#date", Convert.ToDateTime(textBox_tarikh.Text));
cmd.Parameters.AddWithValue("#resit", textBox_resit.Text);
cmd.Parameters.AddWithValue("#payment", textBox_bayaran.Text);
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "pembayaran_table");
connection.Close();
dataGridView3.DataSource = ds;
dataGridView3.DataMember = "pembayaran_table";
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved Successfully");
}
catch (Exception ex)
{
//throw new Exception("Error " + ex.Message);
MessageBox.Show("Receipt No. is already use");
}
}
You can try :
private void btn_add_Click(object sender, EventArgs e)
{
string bResult = textBox_ic.Text;
if (textBox_tarikh.Text == "" || textBox_resit.Text == ""||textBox_bayaran.Text == "")
{
MessageBox.Show("Please Fill In The Blank");
}
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd ;
try
{
if(connection.State == ConnectionState.Closed) connection.Open();
cmd = new SqlCommand("INSERT Pembayaran (Description, Date, No_Resit, Payment, Studentic) VALUES (#Description, #date, #resit, #payment, #val)", connection);
cmd.Parameters.AddWithValue("#val", bResult);
cmd.Parameters.AddWithValue("#Description", label4.Text);
cmd.Parameters.AddWithValue("#date", Convert.ToDateTime(textBox_tarikh.Text));
cmd.Parameters.AddWithValue("#resit", textBox_resit.Text);
cmd.Parameters.AddWithValue("#payment", textBox_bayaran.Text);
cmd.Executenonquery();
SqlDataAdapter da = new SqlDataAdapter("Select * from Pembayaran",connection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView3.DataSource = dt;
}
catch(Exception ex)
{
}
finally
{
if(connection.State == ConnectionState.Open) connection.Close();
}
}
You just need to update your DataGridView's Datasource after inserting record to DB.
Firstly, I don't see any data binding code in your snippet such as DataGridView.DataSource = " ", DataGridView.DataBind();
What you can try to do it after inserting data, make use of ##IDENTITY to retrieve the id of what you have inserted. Then make use of the id retrieved to capture the new record.
##IDENTITY
I have noticed in your code snippet, you used the same query.
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
You should write another SqlStatement and call it from SqlDataAdapter
For example:
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");
Populating a DataSet from a DataAdapter
what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");