Update Query not working C# asp.net - c#

In this page only this query
c1.cmd.CommandText = "update mechprofile set mech_status ='busy' where mech_regid ='" + alotmech + "'";
is working, rest of the queries are not working.
public partial class customercare_alotmechanic : System.Web.UI.Page
{
Class1 c = new Class1();
Class1 c1 = new Class1();
int sno;
string license;
string status;
string alotmech;
string mechregid;
string mrg;
protected void Page_Load(object sender, EventArgs e)
{
try
{
sno = Convert.ToInt32((Request.Form["sno"]));
status = Request.Form["sta"];
alotmech = Request.Form["Sel"];
mrg = Request.Form["mechregid"];
if (alotmech.Equals("Alloted"))
{
c.con.Open();
c.cmd.CommandText = "update probprofile set Status = 'done' where Sno ='" + sno + "'";
c.cmd.ExecuteNonQuery();
c.con.Close();
c.con.Open();
c.cmd.CommandText = "update mechprofile set mech_status = 'free' where mech_regid ='" + mrg + "'";
c.cmd.ExecuteNonQuery();
c.con.Close();
}
else
{
c.con.Open();
c.cmd.CommandText = "update probprofile set mechregid = '" + alotmech + "' where Sno ='" + sno + "'";
c.cmd.ExecuteNonQuery();
c.con.Close();
c1.con.Open();
c1.cmd.CommandText = "update mechprofile set mech_status ='busy' where mech_regid ='" + alotmech + "'";
c1.cmd.ExecuteNonQuery();
c1.con.Close();
}
}
finally
{
string strScript = "<script>";
strScript += "alert('ALOT MECHANIC PAGE..');";
strScript += "window.location='problemstatus.aspx';";
strScript += "</script>";
Page.RegisterClientScriptBlock("strScript", strScript);
}
}
}
In the above code update commands are not working... I have a form on a page with method=post and action se to this page on which update query runs.

Have you tested the values of the variables you are suffixing to the query statement? For example, check whether sno, status, and mrg actually contain valid values before doing the update with those values. If any of them is null or contain an unacceptable value as regards to your table design, then the query will fail.
What's the error statement you get? I see that you have a try...finally but no catch. You should always catch exceptions to promote better error handling.

Check if your parammeters' value is correct:
If your data type is Nvarhcar so you should use N before your constants data. i.e.
"... column= N'"+ value+ "'"
Or if your data type is int so don't use '. i.e.
"... column= "+ value

Related

ExecuteNonQuery CommandText property has not been initialized

When I click on this button, I face with this error:
executenonquery commandtext property has not been initialized
private void button_FirstStep_Click(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection(Yahya.strcon);
Conn.Open();
int CurrentCount = Convert.ToInt32(label_CurrentCount.Text);
string strcom1 = "select * from vm1 where count = '" + (CurrentCount - 1) + "' and benchmarkid = '" + Structure.BenchmarkID + "' ";
SqlCommand cmd = new SqlCommand(strcom1, Conn);
SqlDataReader reader = cmd.ExecuteReader();
string strcom = "";
while (reader.Read())
{
if (reader["vmid"].ToString() != "")
{
string vmid = reader["vmid"].ToString();
strcom += "update vm1 set pmid = (select pmid from vm1 as VM2 where benchmarkid = '" + Structure.BenchmarkID + "' and vm2.count ='" + (CurrentCount - 1) + "' and vm2.vmid ='" + vmid + "' ) where count = '" + CurrentCount + "' and vmid = '" + vmid + "' and benchmarkid = '" + Structure.BenchmarkID + "' \n";
}
}//end of while
reader.Close();
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}
Rene is quite right about his comment, looks like your reader.Read() returns false and that's why your code never goes into your while loop and your CommandText is assigned to "", that's why ExecuteNonQuery throws
ExecuteNonQuery: CommandText property has not been initialized
You can check your strcom is empty string or not to solve your problem but I see more wrong things in your code other than that..
Looks like your count column is numeric value but you supplied your CurrentCount - 1 as a character with single quotes. If it is not numeric, it should. Read: Bad habits to kick : choosing the wrong data type
Based on it's name, benchmarkid should(?) be numeric types as well.
You can solve this two problem with using parameterized queries because this kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection, command and reader automatically instead of calling Close or Dispose methods manually.
Open your connection just before you execute your command.
You could solve this by simply debugging before asking.
The reason for this error is presumably that your first request returns zero results.
So reader.Read() is always false and strcom stays empty. You set an empty string as cmd.CommandText before the call to ExecuteNonQuery().
To solve this, simply check if the string is empty and execute the last query only if it is not empty:
...
reader.Close();
if (!string.IsNullOrEmpty(strcom))
{
cmd.CommandText = strcom;
cmd.ExecuteNonQuery();
}

SqlCommand AddWithValue and if statements issue with gridview

I am trying to build a web form that uses SQL queries to help populate various dropdowns and display results in gridviews, the issue i'm having at the moment is getting the user input to replace varibles in the SQL query.
My query is as follows:
SELECT TOP 50
'Select' AS 'Select',
id_ref AS 'Number',
created_date AS 'Date Created',
address 'Address',
category AS 'Category',
borough
FROM Events
WHERE location_address LIKE '%%'
AND borough #borcond
AND admin_ref #stacond
AND id_ref #Numcond
AND category #cat
AND created_date #startDate
AND created_date #endDate
AND address LIKE #Addresscond
ORDER BY id_todays_date DESC
My C# code is as follows:
public void SQLQueryv2(
string AddressSel,
string startDateSel,
string endDateSel,
string incidentSel,
string borsel,
string stasel,
string numsel)
{
//this is filled in really
SqlConnection Connection = new SqlConnection(
"Data Source=;Initial Catalog=;User=;Password=;");
string sqlquery = <<as above>>
try
{
SqlCommand Command = new SqlCommand(sqlquery, Connection);
Connection.Open();
if (borsel == "Select Borough")
{
Command.Parameters.AddWithValue("#borcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= " + "'" + borsel + "'");
}
if (stasel == "Select Town")
{
Command.Parameters.AddWithValue("#stacond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#borcond","= "+ "'" + borsel + "'");
}
if (startDateSel == "")
{
Command.Parameters.AddWithValue("#startDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#startDate",
">= CONVERT(datetime," + "'" + startDateSel + "'" + ",103)");
}
if (endDateSel == "")
{
Command.Parameters.AddWithValue("#endDate", " = IS NOT NULL");
}
else
{
Command.Parameters.AddWithValue(
"#endDate",
">= CONVERT(datetime," + "'" + endDateSel + "'" + ",103)");
}
if (incidentSel == "Select Category")
{
Command.Parameters.AddWithValue(
"#cat",
" in ('cat a','cat b','cat c')");
}
else
{
Command.Parameters.AddWithValue(
"#cat",
" AND category =" + "'" + incidentSel + "'");
}
if (AddressSel == "")
{
Command.Parameters.AddWithValue("#Addresscond", "%%");
}
else
{
Command.Parameters.AddWithValue("#Addresscond","%" + AddressSel + "%");
}
if (numsel == "")
{
Command.Parameters.AddWithValue("#Numcond", " = IS NOT NULL ");
}
else
{
Command.Parameters.AddWithValue("#Numcond", "= " + "'" + numsel + "'");
}
//use adapter to populate dataset...
SqlDataAdapter DataAdapter = new SqlDataAdapter(sqlquery, Connection);
DataTable DataTable = new DataTable();
DataAdapter.SelectCommand = Command;
DataAdapter.Fill(DataTable);
//then bind dataset to the gridview
GridView1.AutoGenerateColumns = true;
GridView1.DataSource = DataTable;
GridView1.DataBind();
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Green;
lblResults.Text = "Your search has returned "
+ Dataset.Tables[0].Select(
"'Incident Number' IS NOT NULL").Length.ToString()
+ " records.";
}
catch (Exception err)
{
lblResults.Visible = true;
lblResults.ForeColor = System.Drawing.Color.Red;
lblResults.Text =
"An error has occurred loading data into the table view. ";
lblResults.Text += err.Message;
}
}
When run, the Gridview doesn't populate and the query (when investigated) it still has the variables and not the 'is nulls' or user inputs.
I think its something to so with the IF statements but i'm entirely sure. I think i just need another pair of eyes on this, any help would be appreciated.
Bit more info:
If i take out the sqlCommand bits it works perfectly with the IF statements, i'm trying to stop people from using malicious SQL queries.
This really isn't the correct way to use parameters. You should only assign values to them, not add comparison operators. Here's an example of how to "fix" your query for the #borcond parameter
...
AND ((#borcond = 'Select Borough' AND borough IS NOT NULL)
OR borough = #borcond)
...
Note: you don't need the equal sign with IS NOT NULL
And replace the if-else with
Command.Parameters.AddWithValue("#borcond", borsel);
You'll need to do similar changes for all of your parameters. The trick here is to basically move your if-else logic from the code into the sql query.
Additionally I don't think you need the location_address LIKE '%%' in your query as that just matches everything.
What juhar said. You've got the wrong idea about parameters. They're parameters and not text substitution. Here's an example of a valid query:
Select firstname, lastname from contacts
where ssn = #ssn
And in your code you'd say
Command.parameters.AddWithValue("#ssn","123-45-6789")

No value given to one or more parameters

So I input some data into textbox then I click this button
private void button2_Click(object sender, EventArgs e)
{
command.Connection = connect;
if (idkaryawantxt.Text != "")
{
string q = "UPDATE tableAbsensi SET Absen_keluar =('" + (DateTime.Now.ToString("hh:mm")) + "') WHERE ID ='" + idkaryawantxt.Text.ToString() + "' AND Tanggal ='" + (DateTime.Now.ToString("MM-dd-yyyy")) +"'";
dosomething(q);
}
this.Close();
}
Then it says
No value given to one or more parameters
The table looked like this :
Check not only if idkaryawantxt is empty but also if it is not null:
if (string.IsNullOrEmpty(idkaryawantxt.Text))
{
var currentDateTime = DateTime.Now;
string q = "UPDATE tableAbsensi SET Absen_keluar ='"
+ currentDateTime.ToString("hh:mm") + "' WHERE ID ='"
+ idkaryawantxt.Text + "' AND Tanggal ='"
+ currentDateTime.ToString("MM-dd-yyyy") +"'";
dosomething(q);
}
Secondly the brackets here (DateTime.Now.ToString("hh:mm"))and here (DateTime.Now.ToString("MM-dd-yyyy")) are not needed.
You do not need to convert idkaryawantxt.Text to string (idkaryawantxt.Text.ToString()), as it is already a string.
You do not need brackets here SET Absen_keluar =('"and here "') WHERE ID ='" .
What is more it might be useful to set the DateTime.Now to a variable instead of calling it twice, because in some exceptional cases it could give you two different values.
And finally: avoid creating your queries in the way you did in this case. It is not an elegant way of creating queries + it is not secured against SQL injections.

Error converting data type varchar to numeric. 1-17-2014

I am having a problem inserting a record, the error says, "Error converting data type varchar to numeric."
This is my set of codes:
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
txtPONo.Text + "', '0', 'Agent', '" +
txtInvoiceNo.Text + "', '" +
lblTotal.Text + "', 'Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
txtOrderNo.Text = nShoppingCart.ToString();
cmdInsert.ExecuteNonQuery();
cn.Close();
}
the highlighted part is the
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
I cannot seem to know where is the problem? thank you for your help.
I think you have taken "CustomerNo" field in database numeric field and you are trying to insert varchar or string value in that field as i am able to see your code in which you are putting "txtCustomerNo.Text" which will contain string value. You should convert your value fisrt in int or whatever you have taken your database field.
Hopefully this will be helpful for you.
Can you run the script without the Convert method. Replace it with:
string nShoppingCart = cmdInsert.ExecuteScalar().ToString();
Then see what nShoppingCart value is, and see if that would ever convert to an integer.
Try adding following part
Convert.ToInt16(lblTotal.Text)

Issues with the update query SQL

am writing a c# code in which am trying to update 4 of the 10 columns of the table. Here is my function type in which am sending arguments for the query:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
Now what happens is that i call this function somewhere in my program providing values in argument:
checkout_visitor(chk_in,chk_out,t_out,dt_out,idcardnum);
The query am using to update my columns is given by:
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = "+ v_idd;
Given me exception incorrect syntax near chkout. Where am i wrong?? is the syntax correct? how do i correct it?
code:
public int checkout_visitor(int check_inn, int checkout, String time_out, String date_out, String cnic)
{
try
{
connection.Open();
String query = "select v_id from visitor where visitor.cnic=" + cnic;
command = connection.CreateCommand();
command.CommandText = query;
visitor_id = command.ExecuteScalar().ToString();
int v_idd = Int32.Parse(visitor_id);
String query2 = " UPDATE visit_detail SET[check_in] = " + check_inn + "[check_out] = " + checkout + "[time_out] = " + time_out + "[date_out] =" + date_out + "where visit_detail.v_id = " + v_idd;
//String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = " + time_out + ",[date_out] =" + date_out + " where visit_detail.v_id = " + v_idd;
command = connection.CreateCommand();
command.CommandText = query2;
int result = command.ExecuteNonQuery();
connection.Close();
return result;
}
catch (Exception e)
{
return -1;
}
}
Problem :
1.you are not seperating the Parameters properly using comma , .
2.you are not giving the sapace between SET and check_in parameter.
Try This:
String query2 = "UPDATE visit_detail SET [check_in] = " + check_inn + ",[check_out] = " + checkout + ",[time_out] = '" + time_out + "',[date_out] ='" + date_out + "' where visit_detail.v_id = "+ v_idd;
Do you see the resulting query? It seems to me you're missing some comma, but you should print (and post) the resulting query to have a better understanding of the issue.
You are missing ',' between the column names.
Its like Update Table Set col1=3,col2='test'
The problem is that query2 string will be something along the lines:
UPDATE visit_detail SET[check_in] = " 1[check_out] = 2[time_out] = some time[date_out] =some datewhere visit_detail.v_id = 5
So you can already see that there's datewhere that is incorect, there are also no ' characters around string parameters, and no commas between parameters.
Quick fix to that would be:
String query2 = String.Format("UPDATE visit_detail SET [check_in]={0}, [check_out]={1}, [time_out]='{2}', [date_out]='{3}' where visit_detail.v_id={4};", check_inn, checkout, time_out, date_out, v_idd);
But this is still not valid. If time_out contains ' characters, you'll again receive an error.
What you should really use is this:
SqlCommand.Parameters
This is a proper way of passing paramters to your command, all the problems will be taken care of for you.

Categories

Resources