I am having trouble with UPDATE and DELETE data in database when working with ASP.NET web form, the code work well with Windows form so I don't know what I did wrong. The code is suppose to update the Gridview with new edited data but when I click edit button, nothing happen to the gridview as well as the datatable.
This is just an exercise that there is no security requirement so I just want to know how to make it work first.
protected void Edit_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = ("UPDATE WareHouse SET [Name] = '" + Name_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Number] = '" + Number_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Storage] = '" + Storage_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Shelf] = '" + Shelf_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
command.CommandText = ("UPDATE WareHouse SET [Brand] = '" + Brand_Field.Text + "' WHERE [Number] = '" + selectedName + "'");
command.ExecuteNonQuery();
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM WareHouse", sqlCon);
DataTable ds = new DataTable();
ad.Fill(ds); // Fill t with data from Adapter a
GridView1.DataSource = ds; // Get data from Source t
GridView1.DataBind();
}
and for delete data
protected void Remove_btn_Click(object sender, EventArgs e)
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
SqlCommand command = new SqlCommand();
command.Connection = sqlCon;
command.CommandText = "DELETE FROM WareHouse WHERE [Name] = '" + Name_Field.Text + "' AND [Number] = '" + selectedNumber + "' AND [Storage] = '" + selectedStorage + "' AND [Shelf] = '" + selectedShelf + "' AND [Brand] = '" + selectedBrand + "'";
command.ExecuteNonQuery();
clear();
showData();
}
Aside these 2 function, there are other two that do adding and searching from database which also use SqlCommand and they work fine without problem. Is there any problem with my query?
Storage, Shelf and Brand wouldn't be updated since you are updating [Number] to have the value of Number_Field.Text and then comparing with selectedName in where clause.
It will help you a great deal to put all this SQL code in SP with parameters and call it from ASP.Net code.
Ok.I also faced this issue back when I was learning ASP.NET.
But i had a little different env.
I had a datagrid to play with and any updates in datagrid content should reflect back in DB table upon clicking update button.
So I had below query to populate the grid.
Try
Dim UpperCase As String = UCase(HostnameTextBox.Text)
Dim sql As String = "select * from HOST_DETAILS where upper(HOSTNAME) like '%" + UpperCase + "%'"
da = New OracleDataAdapter(sql, conn)
ds.Clear()
da.Fill(ds, "TEST")
DataGridView1.DataSource = ds.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
And the below one to update the table on the Update button click.
conn.Open()
Try
Dim ocb As New OracleCommandBuilder
ocb = New OracleCommandBuilder(da)
da.Update(ds, "TEST")
MessageBox.Show("Information Updated")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
conn.Close()
Also make sure DataAdapter da is global and is defined right after public class so it can be accessed from both.
Dim da As New OracleDataAdapter
Hope this helps.
Related
I'm trying to update my data in C# Win Form.
I created a button "update", but whenever I run it, I don't see any changes in the table and any occurring errors
void insertdata() {
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM airport";
adapter.SelectCommand = cmd;
table.Clear();
adapter.Fill(table);
dgv.DataSource = table;
}
private void button_update_Click(object sender, EventArgs e)
{
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE airport SET p_name = '"+textBox2.Text+ "',p_age = '" + textBox3.Text + "', c_name = '" + textBox4.Text + "', date = '" + textBox5.Text + "', city_t = '" + textBox6.Text + "', city_f ='" + textBox7.Text + "', trip_num = '" + textBox8.Text + "', plane_type = '" + textBox9.Text+"' WHERE p_id = '"+textBox1+"'";
cmd.ExecuteNonQuery();
insertdata();
}
I've tried to add
connection.Open();
connection.Close();
However, I keep getting: "System.InvalidOperationException: "The connection was not closed. The connection is open."
Could there be any change in my code for updating the rows in the table, as whenever I run it I don't get any errors.
Please note the you wrote
WHERE p_id = '"+textBox1+"'
Instead of
WHERE p_id = '"+textBox1.Text+"'
Probably you don't have an ID that equals to the textBox...
I began to show my DataGrid on a form is created I would like when I course id, rollno. or enroll no but when I execute this code than show the following problem:
Conversion failed when converting the varchar value 'System.Windows.Forms.ComboBox+ObjectCollection' to data type int
private void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand(
"select COURSE_Id, ROLL_NO, ENROLL_NO, Sub_P_CODE, STUDENT_NA, th_a_o, th_b_o, th_c_o " +
"FROM annual_2018 " +
"where COURSE_ID = '" + course_id.Items.ToString() + "' " +
"and (ROLL_NO = '" + txtRoll.Text + "' OR ENROLL_NO = '" + TxtEnroll.Text + "')",
con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
Enroll_no.DataSource = dt;
con.Close();
}
You have passed the whole ComboBox, you need to specify the SelectedValue of your ComboBox. Your COURSE_ID column in the table is an int datatype and that is what you need to pass it. Also you should always use parameterized queries to avoid SQL Injection. Your code should be something like this:
int selectedValue = Convert.ToInt32(course_id.SelectedValue.ToString());
cmd = new SqlCommand("select COURSE_Id, ROLL_NO, ENROLL_NO, Sub_P_CODE, STUDENT_NA," +
" th_a_o, th_b_o, th_c_o FROM annual_2018 where COURSE_ID = #courseId" +
" and (ROLL_NO = #ROLL_NO OR ENROLL_NO = #ENROLL_NO)", con);
command.Parameters.AddWithValue("#courseId", selectedValue );
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue. See this Can we stop using AddWithValue() already?
cmd.Parameters.Add("#courseId", SqlDbType.Int).Value = selectedValue;
Please help me to understand where I go wrong. ok let's go!
2 DataGridViews, in first I'm store services in second order list.
when I push button Save, this code will happen:
public void insert_sales_list()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
SQLiteCommand cmd = new SQLiteCommand("insert into sales_list (sales_created_date, sales_created_name, emp_name, cust_phone, cust_name, planned_date, planned_time, service_name, discount, price, order_id) values (#ocd, #ocn, #emp, #c_phone, #c_name, #p_date, #p_time, #sn, #disc, #price, #o_id)", conn);
cmd.Parameters.AddWithValue("#ocd", DateTime.Now);
cmd.Parameters.AddWithValue("#ocn", lblLoginUser.Text);
cmd.Parameters.AddWithValue("#emp", dgvOrderList.CurrentRow.Cells[1].Value.ToString());
cmd.Parameters.AddWithValue("#c_phone", dgvOrderList.CurrentRow.Cells[2].Value.ToString());
cmd.Parameters.AddWithValue("#c_name", dgvOrderList.CurrentRow.Cells[3].Value.ToString());
cmd.Parameters.AddWithValue("#p_date", dgvOrderList.CurrentRow.Cells[5].Value);
cmd.Parameters.AddWithValue("#p_time", dgvOrderList.CurrentRow.Cells[6].Value.ToString());
cmd.Parameters.AddWithValue("#sn", row.Cells[0].Value.ToString());
cmd.Parameters.AddWithValue("#disc", dgvOrderList.CurrentRow.Cells[4].Value.ToString());
cmd.Parameters.AddWithValue("#price", row.Cells[1].Value.ToString());
cmd.Parameters.AddWithValue("#o_id", dgvOrderList.CurrentRow.Cells["order id"].Value);
cmd.ExecuteNonQuery();
string sql = "update order_list set status = 'Saved' where id = '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "'";
cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
By this code you see that I just insert data from Order List to Sales List, user choose service or services from DataGridView.Service, he can take any service from the list.
This code works very well.
Next step. I have another table where each service have own materials, for example - men's haircut have soap, shampoo and tissue paper in materials. And I need to insert these data in SalesMaterials Table. And I think code is wrong, please help me to find this error? code:
public void insert_sales_materials()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
string Query = "insert into sales_list_materials(order_id, material_id, norma, created_name, creation_date) " +
"values( select '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "', a.material_id, a.norma, '" + lblLoginUser.Text + "', '" + DateTime.Now + "' from service_materials a where a.service_id = '" + row.Cells[2].Value + "')";
SQLiteCommand cmd = new SQLiteCommand(Query, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Error:
Additional information: SQLite error
near "select": syntax error
Ok I got it!
when you insert data with select, please did not use word values =))
correct code for all of you:
public void insert_sales_materials()
{
conn.Open();
foreach (DataGridViewRow row in dgvService.SelectedRows)
{
string Query = "insert into sales_list_materials(order_id, material_id, norma, created_name, creation_date) " +
"select '" + dgvOrderList.CurrentRow.Cells["order id"].Value + "', a.material_id, a.norma, '" + lblLoginUser.Text + "', '" + DateTime.Now + "' from service_materials a where a.service_id = '" + row.Cells[2].Value + "'";
SQLiteCommand cmd = new SQLiteCommand(Query, conn);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Hi I have an access table called equipment table and a win form with multiple comboboxes the first three work but they are getting distinct values from the Access table. The third however is receiving input from the comboboxes Manufacturer_cmbBx and Type_cmbBx which work. I have used the same code for all the comboboxes and only the Select query has changed. The Diagnostic tool in VS shows that the right values are being passed into the Select query. yet the combobox remains empty. I have called for the combobox to be changed on the SelectedValueChanged event of the combobox Type_cmbBx
private void LoadModel_cmbBx()
{
string strCon = Properties.Settings.Default.Database2ConnectionString;
using (OleDbConnection conn = new OleDbConnection(strCon))
{
try
{
string strSql = "Select Model from EquipmentTable where [Manufacturer] = '" + Manufacturer_cmbBx.Text + "' and [Type] = '" + Type_cmbBx.Text + "'";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
DataSet ds = new DataSet();
adapter.Fill(ds);
Model_cmbBx.DataSource = ds.Tables[0];
Model_cmbBx.ValueMember = "Model";
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Using The Dataset Viewer in VS I could see that only the Model column was in there so I changed my statement to
"Select DISTINCT * from EquipmentTable where Type = '" + Type_cmbBx.Text + "' and Manufacturer = '"+ Manufacturer_cmbBx + "'";
This still didn't work but
"Select DISTINCT * from EquipmentTable where Type = '" + Type_cmbBx.Text + "'";
Works as does
string strSql = "Select DISTINCT * from EquipmentTable where Manufacturer = '" + Manufacturer_cmbBx + "'";
only when I try to add a second combobox does the Dataset remain empty. Any thoughts as to why this is?
I am getting Unclosed quotation mark after the character string ''. and I have tried everything any help would be greatly appreciated.
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sipConnectionString"].ConnectionString);
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
string query = "select dealercode, dropdate, couponno from coupon where dealercode = '" + DEALERCODETextBox.Text + "' and dropdate = '" + DROPDATETextBox.Text + "' and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#totalrev", GRANDTOTALTextBox.Text);
cm.ExecuteNonQuery();
conn.Close();
In the last of your query string
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"','";
replace +"','"; with "'";
Note: Your query string also lack of Parameters
You use paramters to add the values, but you don't use the parameters in the query:
string query = "select dealercode, dropdate, couponno from coupon where dealercode = #dealercode and dropdate =#dropdate and COUPONNO = #couponcount;";
SqlCommand cm = new SqlCommand(query, conn);
cm.Parameters.AddWithValue("#couponcount", COUPONCOUNTTextBox.Text);
cm.Parameters.AddWithValue("#dealercode ", DEALERCODETextBox.Text);
cm.Parameters.AddWithValue("#dropdate ", DROPDATETextBox.Text);
Replace with this line:
string query = "select dealercode, dropdate, couponno
from coupon where dealercode = '" + DEALERCODETextBox.Text + "'
and dropdate = '" + DROPDATETextBox.Text + "'
and COUPONNO = '" + COUPONCOUNTTextBox.Text +"'";
SqlCommand cm = new SqlCommand(query, conn);