Incorrect syntax near the keyword 'and' - asp.net

I am trying to filter the gridview with the help of a few checkboxlists and it works absolutely fine.It is all real time since i am using a update panel.Now when i try to add one more filer i.e couple of datepickers to filter the gridview depending on the two dates,it gives me the error message " Incorrect syntax near the keyword 'and'.". The entire code is given below :
private void BindGrid()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
string query = "Select * from tblAllEvents";
string condition = string.Empty;
string conditionDisability = string.Empty;
string conditionDates = string.Empty;
foreach (ListItem item in cblGender.Items)
{
condition += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(condition))
{
condition = string.Format(" Where Gender IN ({0})", condition.Substring(0, condition.Length - 1));
}
else
{
condition = string.Format(" Where Gender IN ('Male','Female','Mixed')", condition.Substring(0,Math.Max(0,condition.Length - 1)));
}
foreach (ListItem item in cblDisability.Items)
{
conditionDisability += item.Selected ? string.Format("'{0}',", item.Value) : string.Empty;
}
if (!string.IsNullOrEmpty(conditionDisability))
{
conditionDisability = string.Format(" and Disabled IN ({0})", conditionDisability.Substring(0, conditionDisability.Length - 1));
}
if(txtEventStart.Text == null)
{
txtEventStart.Text = "01/01/1900";
}
if(txtEventEnd.Text == null)
{
txtEventEnd.Text = "01/01/2050";
}
conditionDates = string.Format(" and EventStart between {0} and {1}",txtEventStart.Text,txtEventEnd.Text);
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand(query + condition + conditionDisability + conditionDates))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
cmd.Connection = con;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
Please note the problem arises on when i include 'conditionDates' in the query. What can be the other ways to make the query work.
Edit : As i said earlier, the problem lies in the below code
if(txtEventStart.Text == null)
{
txtEventStart.Text = "01/01/1900";
}
if(txtEventEnd.Text == null)
{
txtEventEnd.Text = "01/01/2050";
}
conditionDates = string.Format(" and EventStart between {0} and {1}",txtEventStart.Text,txtEventEnd.Text);

You are missing apostrophes around the values:
conditionDates = string.Format(" and EventStart between '{0}' and '{1}'", txtEventStart.Text, txtEventEnd.Text);
Note however that code like this is wide open for SQL injection attacks. You should use parameters in the query instead:
conditionDates = " and EventStart between #EventStart and #EventEnd";
Then you add parameters to the command object parameter collection to supply the values to the query:
cmd.Parameters.Add("#EventStart", SqlDbType.DateTime).Value = txtEventStart.Text;
cmd.Parameters.Add("#EventEnd", SqlDbType.DateTime).Value = txtEventEnd.Text;

You clearly have a SQL syntax error. First debug your code and get the resulting query and run it separately in SQL Server. You will inspect it better in that way.
It's about how you are concatenating the SQL query when you add that part.

Related

I keep getting an error that I don't understand. Must declare the scalar variable "#publish_dategenre"

This is my code of update button in web app and whenever I'm trying to click on update button and that time alert message pops up and repeating the same error message i.e. must declare scalar variable #publish_dategenre.
void getGamebyID()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM game_inventory WHERE game_id = '" + TextBox1.Text.Trim() + "';", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1)
{
TextBox2.Text = dt.Rows[0]["game_name"].ToString();
DropDownList2.SelectedValue = dt.Rows[0]["community_name"].ToString().Trim();
TextBox3.Text = dt.Rows[0]["publish_date"].ToString().Substring(0, 10);
TextBox10.Text = dt.Rows[0]["game_cost"].ToString();
TextBox6.Text = dt.Rows[0]["game_des"].ToString();
ListBox1.ClearSelection();
string[] genre = dt.Rows[0]["genre"].ToString().Trim().Split(',');
for (int i = 0; i < genre.Length; i++)
{
for (int j = 0; j < ListBox1.Items.Count; j++)
{
if (ListBox1.Items[j].ToString() == genre[i])
{
ListBox1.Items[j].Selected = true;
}
}
}
global_filepath = dt.Rows[0]["game_img"].ToString();
}
else
{
Response.Write("<script>alert('Invalid Game ID');</script>");
}
}
catch (Exception ex)
{
}
}
fire up SQL studio, and paste in that query.
Also, try opening that table - in design mode in sql studio, see if the table exists.
It is possible that the query is actually a kluge such as
SELECT * FROM MySclarFunction(10)
Sometimes people use that syntax and the FROM is not actually a table, but is a scalar function, and that function would thus in fact need value, and that could explain the error.
As others have suggested - do adopt using parameters and not string concentration.

How to check if the value is not null and if not then the value should be displayed in Textbox in ASP.NET

This is my code
SqlConnection con = new SqlConnection(cs);
con.Open();
string query = "select Name from t_identities where Branchid = '" + branchidtext.Text + "' and Accountid = '" + accountidtext.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
string value = cmd.ExecuteScalar().ToString();
if (value != null)
{
nametext.Text = value.ToString();
}
else
{
nametext.Text = "No records Found";
}
}
If the query returs Null then the textbox should return No records found or else it should display the name generated by the query in the text box. Please help.
Probably you are getting error in this line
string value = cmd.ExecuteScalar().ToString();
as it trying to convert a null value to string. Better use Convert.ToString(cmd.ExecuteScalar()) to handle this case.
Your if/else block is ok
SQL's null maps to C#'s DBNull.Value:
var value = cmd.ExecuteScalar();
if (value != DBNull.Value)
{
nametext.Text = (string)value;
}
substitute
string value = cmd.ExecuteScalar().ToString();
with
object value = cmd.ExecuteScalar();
Try this:
string value = "";
if ( (value = cmd.ExecuteScalar().ToString())!= null)
{
nametext.Text=value.ToString();
}

Changing the parameter in sql query of ASP.NET page - with button_click event, sql query in every button click

I have a ASP.NET page which have details in below manner.
Date OfficerID DutyID
25-NOV-13 2 666
26-NOV-13 2 666
27-NOV-13 2 666
28-NOV-13 2 666
29-NOV-13 2 666
30-NOV-13 2 666
01-DEC-13 2 666
02-DEC-13 2 523
The above is being populated in gridview through below code snippet
DataTable table = new DataTable();
string connectionString = GetConnectionString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate and sysdate+18";
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
//DropDownList1.DataSource = table;
//DropDownList1.DataValueField = "";
GridView1.DataSource = table;
GridView1.DataBind();
Now I also have a previous button which should output the same page but with sql query slightly changed
select * from duty_rota where duty_date between sysdate-18 and sysdate;
and with every button click the date parameters should be decreased by 18, i.e with 1st previous button click query will be
sysdate-18 and sysdate
with 2nd click
sysdate-36 and sysdate-18
with 3rd click
sysdate-54 and sysdate-36
and so on...
Please help me how could I acheieve it , I was trying to implement it with a variable associated with Previous buttons button click event which would change with every subsequent click. But I am not really able to accomplish it. Can anybody please guide me on this.
Write below code to handle dynamic query on previous and next button click event :
protected void PrevioseButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(false);
this.BindGrid(sqlQuery);
}
protected void NextButton_Click(object sender, EventArgs e)
{
var sqlQuery = this.GenerateQuery(true);
this.BindGrid(sqlQuery);
}
private string GenerateQuery(bool isNext)
{
if (ViewState["fromDate"] == null && ViewState["toDate"] == null)
{
ViewState["fromDate"] = isNext ? "sysdate+18" : "sysdate-18";
ViewState["toDate"] = isNext ? "sysdate+36" : "sysdate";
}
else
{
var from = ViewState["fromDate"].ToString().Replace("sysdate", string.Empty);
var to = ViewState["toDate"].ToString().Replace("sysdate", string.Empty);
int fromDay = 0;
int toDay = 0;
if (from != string.Empty)
{
fromDay = Convert.ToInt32(from);
}
if (to != string.Empty)
{
toDay = Convert.ToInt32(to);
}
if (!isNext)
{
fromDay = fromDay - 18;
toDay = toDay - 18;
}
else
{
fromDay = fromDay + 18;
toDay = toDay + 18;
}
from = "sysdate";
to = "sysdate";
if (fromDay > 0)
{
from += "+" + fromDay;
}
else if (fromDay < 0)
{
from += fromDay.ToString();
}
if (toDay > 0)
{
to += "+" + toDay;
}
else if (toDay < 0)
{
to += toDay.ToString();
}
ViewState["fromDate"] = from;
ViewState["toDate"] = to;
}
var sqlQuery = "select * from duty_rota where duty_date between " + ViewState["fromDate"] + " and "
+ ViewState["toDate"];
return sqlQuery;
}
private void BindGrid(string sqlQuery)
{
DataTable table = new DataTable();
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
On the button click event, try this:
DataTable table = new DataTable();
string connectionString = GetConnectionString();
if (Session["sysdate"] == null || string.IsNullOrEmpty(Session["sysdate"].ToString()))
Session["sysdate"] = "-18";
else
Session["sysdate"] = "+ " + (Convert.ToInt32(Session["sysdate"]) - 18).ToString();
string sysdate = Session["sysdate"].ToString();
string sqlQuery = "select * from duty_rota where duty_date between sysdate " + sysdate + " and sysdate+18 " + sysdate;
using (OracleConnection conn = new OracleConnection(connectionString))
{
try
{
conn.Open();
using (OracleCommand cmd = new OracleCommand(sqlQuery, conn))
{
using (OracleDataAdapter ODA = new OracleDataAdapter(cmd))
{
ODA.Fill(table);
}
}
}
catch (Exception ex)
{
Response.Write("Not Connected" + ex.ToString());
}
}
GridView1.DataSource = table;
GridView1.DataBind();
Me thoughts an ObjectDataSource control would perfectly provide you with a solution...however then I realized that your pagesize varies!
In such a case you need to have your pagination to be disassociated with the gridview. Meaning pagination should be separate and your data which needs to be displayed in the grid view need to be separate. They may have something like a master-child relationship. It means you'd need separate db calls for fetching "each".
You pagination part could be rendered by a gridview or a data list view.
However, if the pagesize on the gridview is always constant you need read this: http://www.codeproject.com/Articles/13963/Implement-Paging-using-ObjectDataSource-with-GridV

Insert multiple textbox values into sql database

I have 3 textboxes to add Skills, that goes into one column called 'SkillName'.
However, I'm getting this error.
'System.Web.UI.Control' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Web.UI.Control' could be found (are you missing a using directive or an assembly reference?)
But I have used the assembly using System.Web.UI.WebControls;
This is my code to add textboxes-
public void InsertSkillInfo()
{
String str = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=DBNAME;Integrated Security=True";
SqlConnection conn = new SqlConnection(str);
try
{
for (int i = 1; i <= 3; i++)
{
conn.Open();
**string skill = (Page.FindControl("TextBox" + i.ToString())).Text;**
const string sqlStatement = "INSERT INTO Cert (SkillName) VALUES (#SkillName)";
SqlCommand cmd = new SqlCommand(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters["#SkillName"].Value = skill;
cmd.ExecuteNonQuery();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
Page.FindControl will return a Control, but you want a textbox. If you are sure that the control it finds will always be a textbox, then cast it to a textbox.
Either:
string skill = (TextBox)((Page.FindControl("TextBox" + i.ToString()))).Text;
or
var skill = "";
var control = Page.FindControl("TextBox" + i.ToString()) as TextBox;
if(control != null {
skill = control.Text;
}
You need to cast the control to a TexBox so it should be this
string skill = ((TextBox) Page.FindControl("TextBox" + i.ToString())).Text;
You can Try it simply like this
string skill = ((TextBox)(Page.FindControl("TextBox" + i.ToString()))).Text;

Error binding DataAdapter->DataSet->LINQ->ASP.Net DataGrid

I have the following code:
using (SqlConnection cn = new SqlConnection(Connection.Instance.ConnectionString))
{
// Open the connection
using (SqlCommand cmd = new SqlCommand())
{
try
{
cmd.Connection = cn;
cmd.CommandText = "Select Customers.CustomerID, Addresses.AddressCode, Addresses.FirstName, Addresses.LastName, Addresses.Address1, Addresses.City, Addresses.State, " +
"Addresses.Zip, Addresses.Home AS HomePhone, Addresses.Phone AS WorkPhone, Addresses.EmailAddress From Customers " +
"LEFT OUTER JOIN Addresses ON Addresses.ID=Customers.AddressID " +
"Where CustomerType IN ('HomeOwner', 'Home Owner') AND Customers.ResellerID=#ResellerID ";
cmd.Parameters.AddWithValue("#ResellerID", base.UserID);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet dsCustomer = new DataSet();
da.Fill(dsCustomer);
var customers = from c in dsCustomer.Tables[0].AsEnumerable().AsQueryable()
where c.Field<string>("CustomerID") == txtSearchCriteria.Text
select c;
dgCustomers.CurrentPageIndex = 0;
dgCustomers.DataSource = customers;
dgCustomers.DataBind();
}
catch (Exception e)
{
throw new Exception(e.Message + e.StackTrace);
}
finally
{
if ((cn != null) && (cn.State != ConnectionState.Closed))
cn.Close();
}
}
}
Which is giving me the error
AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID 'dgCustomers' when AllowPaging is set to true and the selected data source does not implement ICollection. at System.Web.UI.WebControls.DataGrid.CreateControlHierarchy(Boolean useDataSource)
How do I convert this LINQ query so that it can be pagable?
Note: This is a simplified version of what I'm trying to do. I know in this example I could simply modify the SQL statement to include "And CustomerID=#CustomerID" and bypass LINQ completely. But, in the bigger picture, I can't do that.
The error message is clear, you need to implement your paging logic to take advantage from paging. BTW, to make your code to work just use a ICollection as DataSource, changing this line:
dgCustomers.DataSource = customers.ToList();

Resources