executenonquery is my problem, this code works on other button in different datagridview
here's my code at delete button
private void button4_Click_2(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=XXYZZ\SQLEXPRESS;Initial Catalog=rick_inventiory;Integrated Security=True");
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from tbl_Orders where CustomersID2 = '" + dataGridView5.SelectedRows[0].Cells[0].Value.ToString() + "'";
con.Open();
cmd.Parameters.AddWithValue("#CustomerID2", txtCustomerID2.Text);
cmd.ExecuteNonQuery();
con.Close();
disp_data();
MessageBox.Show("Deleted Successfully");
}
the update code still execute sa code but did not update it
and heres my code for Update button
SqlConnection con = new SqlConnection(#"Data Source=XXYZZ\SQLEXPRESS;Initial Catalog=rick_inventiory;Integrated Security=True");
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Update tbl_Products SET ProductName='" + txtProName.Text +
"',Stocks='" + txtStocks.Text + "',Price='" + txtPrice.Text + "',Description='" +
txtDesc.Text + "',CategoryName='" + txtCat.Text + "' where ProductID ='" + txtProID.Text + "';";
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter("Select * from tbl_Products", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Successfuly Updated");
con.close();
In update there is a syntax problem remove inner side semi colon of update query
While in delete you want to change the line
from
cmd.Parameters.AddWithValue("#CustomerID2", txtCustomerID2.Text);
to
cmd.Parameters.AddWithValue("#CustomerID2", '" + dataGridView5.SelectedRows[0].Cells[0].Value.ToString() + "');
Related
The problem says:
Too few parameters. Expected 1.
Here's my database table:
CustomerOrder [CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate]
Code:
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO CustomerOrder(OrderId, ProdName, ProdPrice, OrderQty, CatName, OrderDate)values('" + txtOrderCode.Text + "','" + txtProdName.Text + "', '" + txtProdPrice.Text + "', '" + txtOrderQty.Text + "', '" + txtCatName.Text + "', '" + txtOrderDate.Text + "')";
cmd.ExecuteNonQuery();
tabControl1.SelectedTab = tabPage1;
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
int ordercode, orderqty;
double price;
string prodname, catname;
ordercode = Convert.ToInt32(txtOrderCode.Text);
orderqty = Convert.ToInt32(txtOrderQty.Text);
price = Convert.ToDouble(txtProdPrice.Text);
prodname = Convert.ToString(txtProdName.Text);
I would recommend you use parametrised queries instead as it will prevent you from Sql Injection Attacks. Here is a small example of how it could work with your code
String SqlCommand = "insert into CUSTOMERORDER values (#OrderId, #ProdName,#ProdPrice,#OrderQty, #CatName,#OrderDate)";
SqlCommand cmd = new SqlCommand(SqlCommand , //ConnectionString);
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.Parameters.AddWithValue("#OrderId", txtOrderCode.Text);
cmd.Parameters.AddWithValue("#ProdName", txtProdName.Text );
cmd.Parameters.AddWithValue("#ProdPrice", txtProdPrice.Text);
cmd.Parameters.AddWithValue("#OrderQty", txtOrderQty.Text);
cmd.Parameters.AddWithValue("#CatName", txtCatName.Text.Text);
cmd.Parameters.AddWithValue("#OrderDate", txtOrderDate.Text);
cmd.ExecuteNonQuery();
conn.Close();
Read up on Sql Injection attacks. Doing it this way is much easier, cleaner and most importantly, safer. Also when looking at your code you are setting the text box values after you have ran the Sql command
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
This code displays an error like this:
System.InvalidOperationException. ExecuteNonQuery: Connection property has not been initialized.
You need to tell your sql command that use this connection(con) to execute the command(cmd).so use an overloaded constructor of the SqlCommand class that takes 2 parameters(cmdText, connection).
SqlCommand cmd = new SqlCommand("update Students set RegNo='" +
RegNo"',Name='" + Name.Text + "',Address=" + Address.text, con);
But it is also possible, to create an instance of SqlCommand class using the parameter less constructor, and then later specify the command text and connection, using the CommandText and Connection properties of the SqlCommand object as shown below.
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
You can use the using statement where the resources are automatically disposed.We don't have to explicitly call Close() method, when using is used. The connection will be automatically closed for us.
int result;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text, con);
con.Open();
result = cmd.ExecuteNonQuery();
}
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
To try to use as following sample code
string constr ="Data Source=localhost;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=1111"
SqlConnection con = new SqlConnection(constr);
I think , in the SQL Command you need to assign the connection
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Students set RegNo='" + RegNo.Text + "',Name='" + Name.Text + "',Address=" + Address.Text);
cmd.Connection = con;
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
//ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
Response.Write("Record saved successfully");
}
Response.Redirect("~/WebForm1.aspx");
}
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update Student set Name='" + Name.Text + "',Address='" + Address.Text + "'where RegNo=" + RegNo.Text);
cmd.Connection = con;//adding this line my error solved
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
I changed my code like above.
Hi guys when I want to update without changing old data I get this error
Syntax error (missing operator) in query expression 'data.[Phone Number]+ ' ' +0770444 +'.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb");
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET data.[Phone Number] = data.[Phone Number]+ ' ' +"+textBox23.Text+" + WHERE data.([ID]) = " + textBox15.Text + " ";
cmd.Connection = con;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt;
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
MessageBox.Show("Data Updated Successfully");
con.Close();
Start using Command Parameters and you will avoid problems like this:
cmd.CommandText = #"UPDATE data SET [Phone Number] = [Phone Number] + ' ' + #NewPhoneNumber WHERE ID = #ID ";
cmd.Parameters.AddWithValue("#ID", textBox15.Text);
cmd.Parameters.AddWithValue("#NewPhoneNumber", textBox23.Text);
cmd.Connection = con;
Also this will protect you from Sql Injection. Be aware you should provide proper naming of your controls(textboxes), this names means nothing for other programmers. Write your columns together PhoneNumber it is annoying to escape them all the time, you are creating more work for yourself for no reason.
Other points wrap your OleDbConnection and OleDbDataAdapter in using blocks
using(OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "\\db\\it.accdb"))
{
con.Open();
//... stuff
DataTable dt;
using(OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
//stuff relate to db adapter
}
}
Using is representing try/catch/finally with calling Dispose() in finally block. This will protect if your code have an exception your connection will be closed. In your current format this is not happening. OleDbDataAdapter is using unmanaged resources so it should be Dispose() too.
Your command seems to be wrong it should be
cmd.CommandText = "UPDATE data SET data.[Phone Number] = " + "'" + data.[Phone Number] + textBox23.Text + "' WHERE data.([ID]) = " + textBox15.Text;
Whereas it is always recommended that we should use the Parameterized Query instead of string concat.
thanks guys I resolved it by this
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE data SET [Phone Number] = [Phone Number]+\n'" + textBox3.Text + "' WHERE ID = " + textBox15.Text + " ";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("New Number Inserted Successfully to ID " + textBox15.Text);
con.Open();
My program will not update my SQL Server database after executing. When I run my program my DataGridView updates when I insert my information, but it will not update itself in the dataTable.
private void button1_Click(object sender, EventArgs e)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES('" + idTextBox.Text + "','" + nameTextBox.Text + "','" + ageTextBox.Text + "')";
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
this.dataTableTableAdapter.Fill(this.employeeDataSet1.dataTable);
conn.Close();
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataTable data = new DataTable();
conn.Open();
adapt.Update(data);
conn.Close();
dataTableDataGridView.DataSource = data;
}
If you created your DataGridView using the designer which added a dataset, bindingsource, and tableadapter, then your DataGridView should be configured correctly out of the box. Try commented out these lines:
//SqlDataAdapter adapt = new SqlDataAdapter(cmd);
//DataTable data = new DataTable();
//conn.Open();
//adapt.Update(data);
//conn.Close();
//dataGridView1.DataSource = data;
I replicated your button_click code and it works locally for me using Sql Express.
Based on your comment i assume the cause is the missing conversion. Using Int32.TryParse you can convert the string to int. Be aware that the ' have to go as well
int id, age;
bool idIsInt = false, ageIsInt = false;
idIsInt = Int32.TryParse(idTextBox.Text, out id);
ageIsInt = Int32.TryParse(ageTextBox.Text, out age);
if(idIsInt && ageIsInt)
{
string query = "INSERT INTO dbo.dataTable(Id,Name,Age) VALUES("
+ id + ",'" + nameTextBox.Text + "',"
+ age + ")";
SqlConnection conn =
new SqlConnection(#"Data Source(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\employee.mdf
;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
conn.Open();
cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
}
This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?