I have a problem when I want to update a row in a database. The page that updates also adds a client but the problem is that when page load detects update button was pressed it seems to keep loading up the variables and I am unable to update my database.
public partial class CustomerInput : System.Web.UI.Page
{
string update, Id, Name, Address, Suburb, Postcode, Age, Email;
protected void Page_Load(object sender, EventArgs e)
{
update = Request.QueryString["Update"];
if (update == "true")
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
Button1.Text = "Update";
Id = Request.QueryString["Id"];
connection.Open();
SqlCommand command = new SqlCommand("Select * from Customer where Id = " + Id, connection);
SqlDataReader read = command.ExecuteReader();
read.Read();
TextBox1.Text = read[1].ToString();
TextBox2.Text = read[2].ToString();
TextBox3.Text = read[3].ToString();
TextBox4.Text = read[4].ToString();
TextBox5.Text = read[5].ToString();
TextBox6.Text = read[6].ToString();
connection.Close();
update = string.Empty;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection("server=localhost; uid=xxxx; pwd=xxxx; database=Customer");
if (Button1.Text == "Update")
{
connection.Open();
SqlCommand command;
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
command = new SqlCommand("UPDATE Customer SET Name = " + "'" + Name + "', " + "Address = " + "'" + Address + "', " + "Suburb = " + "'" + Suburb + "', "
+ "Postcode = " + "'" + Postcode + "', " + "Age = " + "'" + Age + "', " + "Email = " + "'" + Email + "' " + "Where Id =" + Id, connection);
command.ExecuteNonQuery();
connection.Close();
}
if (Button1.Text == "New Client")
{
Name = TextBox1.Text;
Address = TextBox2.Text;
Suburb = TextBox3.Text;
Postcode = TextBox4.Text;
Age = TextBox5.Text;
Email = TextBox6.Text;
Response.Write("Blah");
SqlCommand command = new SqlCommand("INSERT INTO Customer VALUES (" + "'" + Name + "'" + ", " + "'" + Address + "'" + ", " + "'" + Suburb + "'" + ", "
+ "'" + Postcode + "'" + ", " + "'" + Age + "'" + ", " + "'" + Email + "'" + ")", connection);
command.ExecuteNonQuery();
}
Button1.Text = "New Client";
}
}
}
At the start of your page load event you need to add an if statement to check if this is the first time the page loads:
example:
if (!IsPostBack)
{
... add your code here
}
I guess you need to use Page.IsPostBack:
if (Page.IsPostBack)
{
// Do Something ..
{
else
{
// Do something else ..
}
Related
I am using one button named as Button 1. In Button 1 button I perform insert as well as update. I can insert a new row. But when I update the row I had a error on that:
"ORA-00933: SQL command not properly ended ".
My code is:
protected void Button1_Click(object sender, EventArgs e)
{
string UserName = "UserName";
Session["UserName"] = lb1.Text;
TextBox TextBox1 = (TextBox)FindControl("TextBox1");
Label label11 = (Label)FindControl("label11");
TextBox TextBox2 = (TextBox)FindControl("TextBox2");
TextBox TextBox3 = (TextBox)FindControl("TextBox3");
TextBox TextBox4 = (TextBox)FindControl("TextBox4");
DropDownList DropDownList3 = (DropDownList)FindControl("DropDownList3");
DropDownList DropDownList1 = (DropDownList)FindControl("DropDownList1");
TextBox TextBox5 = (TextBox)FindControl("TextBox5");
TextBox TextBox6 = (TextBox)FindControl("TextBox6");
DropDownList DropDownList2 = (DropDownList)FindControl("DropDownList2");
TextBox TextBox7 = (TextBox)FindControl("TextBox7");
TextBox TextBox8 = (TextBox)FindControl("TextBox8");
{
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from
service_master where req_no='" + this.TextBox1.Text.ToString() + "'", con);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
string sql1 = "update service_master set req_no='" + this.TextBox1.Text.ToString() + "' , req_dt='" + label11.Text.ToString() + "',req_by='" + Session["UserName"].ToString() + "', ser_cd='" + TextBox3.Text.ToString() + "',serv_desc= '" + TextBox4.Text.ToString() + "',serv_grp_cd='" + DropDownList3.SelectedItem.Value.ToString() + "',base_uom_cd= '" + DropDownList1.SelectedItem.Value.ToString() + "',sac_cd='" + TextBox5.Text.ToString() + "',ser_long_desc='" + TextBox6.Text.ToString() + "',tax_ind='" + DropDownList2.SelectedItem.Value.ToString() + "',active_ind= '" + TextBox7.Text.ToString() + "',del_ind='" + TextBox8.Text.ToString() + "' where req_no='" + this.TextBox1.Text.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(sql1, con);
cmd.ExecuteNonQuery();
WebMsgBox.Show("Data Successfully Updated");
}
else
{
string sql = "insert into service_master(req_no,req_dt,req_by,ser_cd,serv_desc,serv_grp_cd,base_uom_cd,sac_cd,ser_long_desc,tax_ind,active_ind,del_ind ) values(" + this.TextBox1.Text.ToString() + ",'" + label11.Text.ToString() + "', '" + Session["UserName"].ToString() + "', '" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "','" + DropDownList3.SelectedItem.Value.ToString() + "','" + DropDownList1.SelectedItem.Value.ToString() + "','" + TextBox5.Text.ToString() + "','" + TextBox6.Text.ToString() + "','" + DropDownList2.SelectedItem.Value.ToString() + "','" + TextBox7.Text.ToString() + "','" + TextBox8.Text.ToString() + "')";
OleDbCommand com = new OleDbCommand(sql, con);
com.ExecuteNonQuery();
WebMsgBox.Show("The data for request number" + TextBox1.Text + "is saved");
}
con.Close();
}
}
Your query should look something like this
//insert query
//string sql1 = "INSERT INTO Test(id, name) VALUES(#User_FirstName, #User_LastName)";
//update sample query
string sql1 = "UPDATE Test SET User_FirstName=#User_FirstName, User_LastName=#User_LastName";
SqlCommand cmd = new SqlCommand(smt, _connection);
cmd.Parameters.Add("#User_FirstName", FirstName.Text);
cmd.Parameters.Add("#User_LastName", LastName.Text);
Always use Parameters to preform any database actions. Using user input is very dangerous, look up sql injections.
I got this update thing i cant figure out. The save button seems to be working, its updating the table. I cant seem to figure out the SaveToStock method. It throws me this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''90' at line 1
I tried putting a breakpoint, got this. Break data
Save button
protected void saveButton_Click(object sender, EventArgs e)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
MySQLParser parser = new MySQLParser(connection);
int nonsoldamount = 0;
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
nonsoldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'", "amount"));
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
nonsoldamount = nonsoldamount + oldamount;
}
if (nonsoldamount < Convert.ToInt32(TextBoxAmount.Text))
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are only " + nonsoldamount + " in stock with the selected attributes</span>"));
return;
}
}
else
{
ErrorMessage.Controls.Add(new LiteralControl("<span class=\"error\">There are 0 in stock with the selected attributes</span>"));
return;
}
string sql_query = "";
if (editing)
{
oldamount = Convert.ToInt32(parser.readSelectCommand("SELECT amount FROM dpf_sale where dpfSaleID = " + IDdpfSale, "amount"));
sql_query = "UPDATE dpf_sale SET orderNo = ?orderNo, fk_operatorID = ?operator, status = ?status, amount = ?amount, geometry = ?geometry, length = ?length, CPSI = ?CPSI " +
"WHERE dpfSaleID = ?IDdpfSale";
}
else
{
sql_query = "INSERT INTO dpf_sale (orderNo, fk_operatorID, amount, geometry, length, CPSI, status) " +
"VALUES (?orderNo, ?operator, ?amount, ?geometry, ?length, ?CPSI, ?status)";
}
MySqlCommand myCommand = new MySqlCommand(sql_query, connection);
myCommand.Parameters.AddWithValue("?IDdpfSale", IDdpfSale);
myCommand.Parameters.AddWithValue("?orderNo", TextBoxOrderNo.Text);
myCommand.Parameters.AddWithValue("?operator", DropDownListOperator.SelectedValue);
myCommand.Parameters.AddWithValue("?geometry", DropDownListGeometry.SelectedValue);
myCommand.Parameters.AddWithValue("?length", DropDownListLength.SelectedValue.Replace(',', '.'));
myCommand.Parameters.AddWithValue("?status", DropDownListStatus.SelectedValue);
myCommand.Parameters.AddWithValue("?CPSI", DropDownListCPSI.SelectedValue);
myCommand.Parameters.AddWithValue("?amount", TextBoxAmount.Text);
myCommand.ExecuteNonQuery();
saveToStock();
}
editing = false;
IDdpfSale = 0;
Response.Redirect("dpf_sale.aspx");
}
Stock Change
private void saveToStock()
{
connection = new MySqlConnection(connectionString);
parser = new MySQLParser(connection);
connection.Open();
string sql_stock = "";
string sql_log = "";
int newsaleID;
if (editing == true)
{
sql_stock = "UPDATE dpf_stock SET amount = amount + " + oldamount + " - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
sql_log = "UPDATE dpf_stock_log SET amount = " + TextBoxAmount.Text + " WHERE sale = 1 and id = " + IDdpfSale;
}
else
{
newsaleID = Convert.ToInt32(parser.readSelectCommand("SELECT MAX(dpfSaleID) id FROM dpf_sale", "id"));
sql_log = "INSERT INTO dpf_stock_log (id, assembly, sale, amount) VALUES (" + newsaleID + ", 0, 1, " + TextBoxAmount.Text + ")";
if (parser.hasRows("SELECT * FROM dpf_stock WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue + "'"))
{
sql_stock = "UPDATE dpf_stock SET amount = amount - " + TextBoxAmount.Text + " WHERE geometry = '" + DropDownListGeometry.SelectedValue + "' AND length = '" + DropDownListLength.SelectedValue.Replace(',', '.') + "' AND CPSI = '" + DropDownListCPSI.SelectedValue;
}
else
{
return;
}
}
MySqlCommand myCommand1 = new MySqlCommand(sql_stock, connection);
myCommand1.ExecuteNonQuery();
MySqlCommand myCommand2 = new MySqlCommand(sql_log, connection);
myCommand2.ExecuteNonQuery();
connection.Close();
}
This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me
You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}
I receive this error on cmd.ExecuteNonQuery()... I think I am wrong on cmd.CommandText...
Syntax error (missing operator) in query expression 'Nr_Crt='1' and Varsta '3' and KG '2' and Specie 'Iepure' and Risc'Nu' and Tip1 'Diurn' and Tip2 'Carnivor''.
private void button2_Click_1(object sender, EventArgs e)
{
if (txtNr_Crt.Text != " " & txtVarsta.Text != " " & txtKG.Text != " " & txtSpecie.Text != " " & txtRisc.Text != " " & txtTip1.Text != " " & txtTip1.Text != " " & txtTip2.Text != "")
{
cn.Open();
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta '" + txtVarsta.Text + "' and KG '" + txtKG.Text + "' and Specie '" + txtSpecie.Text + "' and Risc'" + txtRisc.Text + "' and Tip1 '" + txtTip1.Text + "' and Tip2 '" + txtTip2.Text + "'";
cmd.ExecuteNonQuery();
cn.Close();
loaddata();
txtNr_Crt.Text = "";
txtVarsta.Text = "";
txtKG.Text = "";
txtSpecie.Text = "";
txtSex.Text = "";
txtRisc.Text = "";
txtTip1.Text = "";
txtTip2.Text = "";
}
}
You code is vulnerable to SQL injection, i'd fix that.
The issue is that you are missing the = from each of your subsequent and's:
cn.Open();
cmd.Parameters.AddWithValue("#Nr_Crt", txtNr_Crt.Text);
cmd.Parameters.AddWithValue("#Varsta", txtVarsta.Text);
cmd.Parameters.AddWithValue("#KG", txtKG.Text);
cmd.Parameters.AddWithValue("#Specie", txtSpecie.Text);
cmd.Parameters.AddWithValue("#Risc", txtRisc.Text);
cmd.Parameters.AddWithValue("#Tip1", txtTip1.Text);
cmd.Parameters.AddWithValue("#Tip2", txtTip2.Text);
cmd.CommandText = "DELETE from Animale Where Nr_Crt= #Nr_Crt and Varsta = #Varsta and KG = #KG and Specie = #Specie and Risc = #Risc and Tip1 = #Tip1 and Tip2 = #Tip2";
cmd.ExecuteNonQuery();
cn.Close();
This should fix it (and the SQL injection risk)
Your query is wrong. You are missing = when comparing the columns
cmd.CommandText = "DELETE from Animale Where Nr_Crt='" + txtNr_Crt.Text + "' and Varsta='" + txtVarsta.Text + "' and KG='" + txtKG.Text + "' and Specie='" + txtSpecie.Text + "' and Risc='" + txtRisc.Text + "' and Tip1='" + txtTip1.Text + "' and Tip2='" + txtTip2.Text + "'";
foreach(Control ctrl in this.Controls)
{
if (ctrl is TextBox)
{
ctrl.text="";
}
}
For cleaning all textbox at once :) you can create a Method that performs it when you need it