No value given to one or more parameters - c#

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.

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();
}

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)

Update statement in MySQL using C#

I've been building a small inventory system for my workplace and have stumbled on an error that I cannot seem to fix
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
I have no idea what to change here.
Any help would be appreciated.
Problem: You are missing the comma after location parameter in your query.
Solution: You need to separate the parameters using a comma.
Suggestion : Use parameterized queries to avoid SQL Injection Attacks.
Try this:
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
// "UPDATE Inventory SET Inventorynumber='"+ num +"',Inventory_Name='"+name+"', Quantity ='"+ quant+"',Location ='"+ location+"' Category ='"+ category+"' WHERE Inventorynumber ='"+ numquery +"';";
string query = "UPDATE Inventory SET Inventorynumber=#Inventorynumber,Inventory_Name=#Inventory_Name, Quantity =#Quantity ,Location =#Location,Category =#Category WHERE Inventorynumber =#Inventorynumber";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#Inventory_Name",name);
cmd.Parameters.AddWithValue("#Quantity",quant);
cmd.Parameters.AddWithValue("#Location",location);
cmd.Parameters.AddWithValue("#Category",category);
cmd.Parameters.AddWithValue("#Inventorynumber",Convert.ToInt16(numquery));
cmd.Connection = serverconnection;
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
Yes the error is in the missing comma, but this is the result of all that mess with string concatenation that ends always in subtle syntax errors.
Why don't you use a parameterized query? It is a lot simpler to write and you avoid parsing errors like this and (more important) you avoid Sql Injections
private void Update(string num,string name, string quant, string location, string category, string numquery)
{
string query = "UPDATE Inventory SET Inventorynumber=#num, Inventory_Name=#name, " +
"Quantity =#qty,Location =#loc, Category =#cat " +
"WHERE Inventorynumber =#numquery";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, serverconnection);
cmd.Parameters.AddWithValue("#num", Convert.ToInt16(num));
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#qty", quant);
cmd.Parameters.AddWithValue("#loc", location);
cmd.Parameters.AddWithValue("#cat", category);
cmd.Parameters.AddWithValue("#numquery", Convert.ToInt16(numquery));
cmd.ExecuteNonQuery();
this.CloseConnection();
Bind();
}
}
As a side note I have some doubts about some parameters type. Are you sure that quantity is really a string as implied by the presence of quotes around your original value?
Also the numquery and num variables are of type string, you try to convert then to short integer and then you put them inside quotes (meaning that in the database the fields are of type text). This makes no sense at all. If the database expects numbers then do not use quotes, if the database expects strings then do not try to convert. Another reason to use a parameterized query that force you to reflect on these issues.
You are missing a Comma between location and category. You have heard this million times befor i know, but its really much better using prepared statements so you do not have to take care of this kind of things and your code is much more readable.
You missed the comma
Location ='" + location + "', Category ='" + category + "'
// see the `,` between Location and Category
you have missed comma(,) in query:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "' Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Make it as:
string query = "UPDATE Inventory SET Inventorynumber='" + Convert.ToInt16(num) + "',Inventory_Name='" + name + "', Quantity ='" + quant + "',Location ='" + location + "', Category ='" + category + "' WHERE Inventorynumber ='" + Convert.ToInt16(numquery) + "'";
Try removing the ' single quotes around the integers?

Is there a LIKE operator that will include NULL values?

I'm using SQL Server 2008, with a C# front end. I'm trying to pass a SQL string from C# to SQL Server, and there are 2 fields in my WHERE statement that sometimes might contain NULL values. I've got this code on my Page Load in the code-behind (this is for a report that will be placed in a datagrid):
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
string Val_Value = Convert.ToString(Request.QueryString["Val_Val"]);
string Trk_Value = Convert.ToString(Request.QueryString["Trk_Val"]);
string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
string sqlquery;
sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Unique_ID, CCM.CLAIM_ID as Claim_Number, ";
sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CCM.DATE_IMPORTED as Import_Date, CCM.Orig_Open_Date as Original_Review_Date, ";
sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, CCM.BENEFIT_TYPE1 as Benefit_Type1, ";
sqlquery = sqlquery + "CCM.BENEFIT_TYPE2 as Benefit_Type2, CCM.BENEFIT_TYPE3 as Benefit_Type3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
sqlquery = sqlquery + "WHERE CCM.Spare LIKE '" + DDL_Value + "' AND CCM.Cmplt LIKE '" + Val_Value + "' AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.DATE_IMPORTED >= '" + StDt_Value + "' AND CCM.DATE_IMPORTED <= '" + EnDt_Value + "'";
}
The code is sound, it works perfectly fine if a value is selected for all report parameters. The problem is CCM.Spare and CCM.Cmplt can have specific values chosen from a dropdown, or they can be left blank. If left blank, then they need to pull ALL values, whether they're NULL or not. When I leave one (or both) blank, that's where the SQL fails.
I tried checking for blanks and setting the variable equal to '%', but that obviously isn't working; it will only pick up records where there is a value in the field.
I want to do this with one statement if possible before I go cludging it with some If/Then/Else loops.
Is this possible?
try this, I just included the code for the first criteria.
As recommended above, don't concatenate your parameters; the second option is the best way to do it:
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE '" + DDL_Value + "'") + " AND ...";
sqlquery = sqlquery +
"WHERE CCM.Spare " + (DDL_Value == null ? "IS NULL" : "LIKE #par1") + " AND ...";
Additionaly to increase the speed of your query you could do:
sqlquery = sqlquery +
"WHERE " + (DDL_Value != null ? "CCM.Spare LIKE #par1 AND " : "") + "...";
this will ignore the whole criteria on CCM.Spare if your parameter is null.
If you want all possible values of CCM.Spare and CCM.Cmplt, you simply need to leave off the predicate. Build a separate query (preferable using parametrized queries, as marc_s points out) that omits the WHERE clause referencing the empty dropdown value.

Update Query not working C# asp.net

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

Categories

Resources