Missing operand after '=' operator - c#

I have this line of code which uses a dataview view_1 and I'm trying to filter the datagridview by product_name and its size using the RowFilter.
Here is the code:
view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
And when I try to run the application it says Missing operand after '=' operator.
So what is that missing operand?

You have a missing white-space at 'AND
So replace
'AND
with
' AND
Is size a string-column or an int-column? If it's a string you need quotation marks around too:
AND size = '" + cboSize.Text + "'";
or even better, use String.Format as others have commented since it insreases readability:
view_1.RowFilter = string.Format("product_name = '{0}' AND size = '{1}'"
, cboProduct.Text
, cboSize.Text);

Write like this
view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
Missing White space problem
Edit
You can also use string.Format
view_1.RowFilter = String.Format("product_name = '{0}' AND size = {1}", cboProduct.Text,cboSize.Text);

I don't know what is wrong I tried to filter first if the text of cboProduct and cboSize is empty or if no selection has been made and now it's working. Thank you.
Here is the code
if (cboProduct.Text == string.Empty || cboProduct.SelectedIndex == -1 || cboSize.Text == string.Empty || cboSize.SelectedIndex == -1)
{
view_1.RowFilter = string.Empty;
}
else
{
view_1.RowFilter = "product_name = '" + cboProduct.Text + "' AND size = " + cboSize.Text + "";
}

If the variable product_name is having a value that contains a space then the value needs to be wrapped in square brackets in the filter expression:
So,just wrap the variable product_name by pair of square brackets like this
[product_name]
view_1.RowFilter = "[product_name] = '" + cboProduct.Text + "' AND size = " +
cboSize.Text + "";

Related

Is there a way to SELECT a database table using a variable?

I tried this statement:
string query = "SELECT question FROM '" + GlobalVariables.dbQCode + "' WHERE [question_code] = '" + GlobalVariables.questionCode + "' ";
and when I run the code it is giving me an exception:
Syntax error in query. Incomplete query clause.
Is there a way where I can use my variable? I want it to work because I want this code to work also:
if (comboBox1.Text == "General Education"){
GlobalVariables.subjectCode = "GenEd_English";
GlobalVariables.dbQCode = "Gen_Ed_Question_Items";
GlobalVariables.dbCCode = "Gen_Ed_Choice_Bank";
if (comboBox2.Text == "English")
{
GlobalVariables.subjectName = "ENGLISH";
}
}
Single quotes (') denote string literals. Object names, such as table names, should not be surrounded by quotes:
string query = "SELECT question FROM " + GlobalVariables.dbQCode + " WHERE [question_code] = '" + GlobalVariables.questionCode + "' ";
// Quotes removed here --------------^-----------------------------^

Generate Dynamic SQL Query based on Filter Criteria

We have a requirement where Client can Filter Records based on Certain Conditions.
Below is the sample Filter condition which i'm getting in Controller
[
{
"Field":"BANKNAME",
"Operator":"=",
"Value":"35",
"ConditionOperator":"OR",
"DField":"N"
},
{
"Field":"BANKNAME",
"Operator":"=",
"Value":"15",
"ConditionOperator":"AND",
"DField":"N"
},
{
"Field":"PTLOCATION",
"Operator":"=",
"Value":"261",
"ConditionOperator":" ",
"DField":"Y"
]
Based on Filter condition we are generating SQL Query, below is code which we have tried
var FilterCondition = JsonConvert.DeserializeObject<List<RptFilterCondition>>(filter);
string filterCondition = string.Empty;
var lstFilterCondition = FilterCondition.Where(a => a.DField == "N").ToList();
for (int i = 0; i < lstFilterCondition.Count; i++)
{
if (i == 0 && FilterCondition.Count == 1)
{
filterCondition += " custom.CustomeFieldName ='" + lstFilterCondition[i].Field + "' and custom.FIELDVALUE " + lstFilterCondition[i].Operator + "'" + lstFilterCondition[i].Value + "' ";
}
else if (i == 0 && !isanycondition)
{
filterCondition += " (custom.CustomeFieldName ='" + lstFilterCondition[i].Field + "' and custom.FIELDVALUE " + lstFilterCondition[i].Operator + "'" + lstFilterCondition[i].Value + "' )" + lstFilterCondition[i].ConditionOperator;
}
else if (i == FilterCondition.Count - 1)
{
filterCondition += " (custom.CustomeFieldName='" + lstFilterCondition[i].Field + "' and custom.FIELDVALUE " + lstFilterCondition[i].Operator + "'" + lstFilterCondition[i].Value + "' )";
}
else
{
filterCondition += " (custom.CustomeFieldName='" + lstFilterCondition[i].Field + "' and custom.FIELDVALUE" + lstFilterCondition[i].Operator + "'" + lstFilterCondition[i].Value + "' )" + lstFilterCondition[i].ConditionOperator;
}
}
return filterCondition;
Below is Filter condition generated
(custom.CustomeFieldName ='BANKNAME' and custom.FIELDVALUE ='35') OR
(custom.CustomeFieldName='BANKNAME' and custom.FIELDVALUE='15')
and (PTLOCATION = 261)
Below is expected output round bracket should come for same field names
((custom.CustomeFieldName ='BANKNAME' and custom.FIELDVALUE ='35') OR
(custom.CustomeFieldName='BANKNAME' and custom.FIELDVALUE='15'))
and (PTLOCATION = 261)
As mentioned in the comment, the code is vulnerable to the SQL injection.
One alternative is to use ORM, e.g. EF and write your own "engine" to translate from custom query model to the LINQ - https://learn.microsoft.com/en-us/ef/core/querying/
Easier option might be to use OData, which supports user defined querying out of the box with connection to the EF - https://learn.microsoft.com/en-us/odata/webapi/getting-started, https://learn.microsoft.com/en-us/odata/client/query-options

DataView filtering, clarification required on Error

I have created a dataset and also taken a string variable IsExModul which is used during filter my code is as follows
string IsExModul ="Y" ;//By some condition this variable is set to Y
ReportDataView = new DataView(FullReportData, "ReportSection = '" + ReportSection + "' and ( IsPentesterAccess = 'Y' or (" + Convert.ToInt32(LoginUserInfo.Rows[0]["isadmin"]) + " = 1 and IsAdminAccess = 'Y') or (" + Convert.ToInt32(LoginUserInfo.Rows[0]["IsSevTempAcess"]) + " = 1 and IsSevTempAccess = 'Y') or ( " + Convert.ToInt32(LoginUserInfo.Rows[0]["IsWOModule"]) + " = 1 and IsWoModuleAccess = 'Y') or ( " + Convert.ToInt32(LoginUserInfo.Rows[0]["IsExModule"]) + " = 2 and IsExceptionAccess = 'Y') or ( " + Convert.ToInt32(LoginUserInfo.Rows[0]["IsExModule"]) + " IN (1,3) and IsExceptionAccess = 'Y' and "+IsExModul+" = 'Y' ) )"
Its Giving an exception 'Invalid Column name [Y]'
if i remove 'and "+IsExModul+" = 'Y'' from filter condition then it works fine,
why is it considering 'Y' as column.
The trouble is in your last part of the statement and "+IsExModul+" = 'Y' ) )
This is expected to be some SQL text but IsExModul is not a column name where a value is supposed to be 'Y'
I have changed the variable IsExModul from string to integer and now it is working fine as a filter in dataview
int IsExModul =1 ;//By some condition this variable is set to 1
ReportDataView = new DataView(FullReportData, "ReportSection = '" + ReportSection + "' and ( IsPentesterAccess = 'Y' or (" + Convert.ToInt32(LoginUserInfo.Rows[0]["isadmin"]) + " = 1 and IsAdminAccess = 'Y') or (" + Convert.ToInt32(LoginUserInfo.Rows[0]["IsSevTempAcess"]) + " = 1 and IsSevTempAccess = 'Y') or ( " + Convert.ToInt32(LoginUserInfo.Rows[0]["IsWOModule"]) + " = 1 and IsWoModuleAccess = 'Y') or ( " + Convert.ToInt32(LoginUserInfo.Rows[0]["IsExModule"]) + " = 2 and IsExceptionAccess = 'Y') or ( " + Convert.ToInt32(LoginUserInfo.Rows[0]["IsExModule"]) + " IN (1,3) and IsExceptionAccess = 'Y' and " + IsExModul + " = 1 ) )", "SerialNumber", DataViewRowState.CurrentRows);
But still i am not clear why it does not work when it was of string datatype and set to 'Y'
,Can Someone help

Error - No value given for one or more required parameters

I have a problem working on my project.
I'm trying to read a data from an Excel file. It works fine when I'm trying to select rows which are greater than Col1Value but after I add AND Gender = " + gender; it gives me error "NO VALUE GIVEN FOR ONE OR MORE REQUIRED PARAMETERS" I cannot set a specific gender column because It is different on every excel file although column name is same and error appears when I'm trying to fill the DataSet.
if (boxGender.Text != "")
string gender = boxGender.Text;
string col1Name = lbl1stColumn.Text;
string Query = "select * from [data$] where " +
col1Name + " > " + Col1Value +
" AND Gender = " + gender;
OleDbDataAdapter dacol1 = new OleDbDataAdapter(Query, con);
Column1Data.Clear();
dacol1.Fill(Column1Data)
lblStuCount1Col.Text = Column1Data.Tables[0].Rows.Count.ToString();
You need to enclose the string value in single quotes and the column names in square brackets:
string Query = "select * from [data$] where [" +
col1Name + "] > " + Col1Value +
" AND Gender = '" + gender + "'";
I think you might be missing quotes in your SQL query:
string Query = "select * from [data$] where " + col1Name + " > '" + Col1Value + "' AND Gender = '" + gender +"'";
Note single quote (') symbols added.

Dynamically build SQL " OR " query in c#

I am having problem with my asp.net app, in which I am dynamically building SQL query where I am using WHERE clause and adding OR depending on the fields which is entered. here is the scenario.
I have a Four TextBox, out of 2 is DateTime
i would like to search in the database if there is a value in any one text-box and return the results that is bind to a GridView. Now, if there is more than one text-box value then i need to add that as well and build OR in where clause. if there are no values in any one of the text-box then need to return all the results. BUT i am having problem in building the query as i have to go through the if else loop to see if there is any value or null. here is my code.
StringBuilder selectQuery = new StringBuilder();
disCode = SearchTextCouponCode.Text;
disName = SearchTextCouponName.Text;
if(StartDate.SelectedDate != null)
startDate = StartDate.SelectedDate.ToString("yyyy-MM-dd");
if(EndDate.SelectedDate != null)
endDate = EndDate.SelectedDate.ToString("yyyy-MM-dd");
// here is the main thing where i am getting the error
if (!string.IsNullOrEmpty(disCode))
{
selectQuery.Append("DISCOUNTCode = '" + disCode + "'");
}
if (!string.IsNullOrEmpty(disName))
{
selectQuery.Append(" OR DISCOUNTName = '" + disName + "'");
}
if (startDate != "0001-01-01")
{
selectQuery.Append(" OR StartDate = '" + startDate + "'");
}
if(endDate != "0001-01-01")
selectQuery.Append(" OR EndDate = '" + endDate + "'");
// I am using Object Data Source and the method i am passing is taking care of the SQL injection
DataSourceDis.SelectParameters["sqlCriteria"].DefaultValue = selectQuery.ToString();
GridDis.DataBind();
now, when i run the app, and leave the disCode text-box empty, then the query start with OR and gives me the error that incorrect syntax near where ..
please help.
/////////////////////////////////////////////////////////
i am calling another method after building up this query which is taking care of SQL Injection
/////////////////////////////////////////////////////////
The easiest thing you could do is change WHERE to:
WHERE 1=0
And then ensure all of your WHERE conditions start with OR
As Richard has pointed out however, this is not best practice, and you would be better using a stored procedure or LINQ. Using stored procedures you could pass all these parameters to the procedure and then do something like:
AND (#disName IS NULL OR DiscountName=#disName)
You could set all lines to have " OR " at the end (instead of the start), such as...
selectQuery.Append("DISCOUNTCode = '" + disCode + "' OR ");
And then before using the .ToString() have...
if(selectQuery.Length > 0)
{
selectQuery.Length -= 4;
}
If you use the WHERE 1=0 OR solution, you may get performance impacts.
I'd recommend creating a variable to mark the conjunction and changing it when you add a condition
string conjuction = " ";
if (!string.IsNullOrEmpty(disCode))
{
selectQuery.Append(conjunction);
selectQuery.Append("DISCOUNTCode = '" + disCode + "'");
conjuction = " OR ";
}
if (!string.IsNullOrEmpty(disName))
{
selectQuery.Append(conjunction);
selectQuery.Append("DISCOUNTName = '" + disName + "'");
conjuction = " OR ";
}
etc.
I don't know where your inputs are coming from, but be aware of the potential for a SQL injection attack in your current code.
I'd generally do it like this;
var conds = new List<string> ();
// here is the main thing where i am getting the error
if (!string.IsNullOrEmpty(disCode))
{
conds.Add("DISCOUNTCode = '" + disCode + "'");
}
if (!string.IsNullOrEmpty(disName))
{
conds.Add("DISCOUNTName = '" + disName + "'");
}
if (startDate != "0001-01-01")
{
conds.Add("StartDate = '" + startDate + "'");
}
if(endDate != "0001-01-01")
conds.Add("EndDate = '" + endDate + "'");
selectQuery.Append(String.Join(" OR ",conds));
It's a bit hideous building queries like this - better to use prepared statements or LINQ or your own query building class.
A valid Sql query e.g. SELECT * FROM EMPLOYEE WHERE Name = 'Hat' OR SURNAME = 'SOFT'
Looks like you case when the query starts with OR your StringBuilder Appends the query like this
SELECT * FROM EMPLOYEE WHERE OR SURNAME = 'SOFT' and its invalid becuase the OR KEYWORD directly after WHERE
when your disCode text-box is empty then Condition will be "OR DISCOUNTName" which is wrong you can not use "OR" after where
if (!string.IsNullOrEmpty(disCode))
{
selectQuery.Append("DISCOUNTCode = '" + disCode + "'");
}
if (!string.IsNullOrEmpty(disName))
{
selectQuery.Append(" OR DISCOUNTName = '" + disName + "'");
}

Categories