Here is my situation. I want to perform paging, grouping and filtering. So that I am using page_init method. As per my code it's working fine. But user only can give where clause conditions like
For example, I have a textbox in my page. that textbox ID="txtQuery"
, in that textbox user will enter the where clause like itemID='45366'
So i have to make my code like below
cmd.commandText="select * from TABLE_NAME where "+txtQuery.text
So this will show the records. This is the problem now. When I make cmd.commandText
like above it throws an error
System.Data.SqlClient.SqlException: Incorrect syntax near 'where'.
If i give directly, It's working fine without any error.
This is my code
string whereQuery = "";
protected void Page_Init(object sender, EventArgs e)
{
// initialize SomeDataTable
if (IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
whereQuery = getWhereQuery();
//Response.Write("<br/><br/><br/><br/>" + whereQuery);
using (SqlConnection con = new SqlConnection(cs))
{
string query = @"select transactions.storeid as StoreID, YEAR(transactions.Time) Year, MONTH(transactions.Time) Month,
transactionsEntry.TransactionNumber,transactionsEntry.Quantity,
items.ItemLookupCode,items.DepartmentID,items.CategoryID,items.SubDescription1,
suppliers.SupplierName,suppliers.Code
FROM [HQMatajer].[dbo].[Transaction] as transactions
RIGHT JOIN [HQMatajer].[dbo].[TransactionEntry] as transactionsEntry
ON transactions.TransactionNumber=transactionsEntry.TransactionNumber
INNER JOIN [HQMatajer].[dbo].[Item] as items
ON transactionsEntry.ItemID=items.ID
INNER JOIN [HQMatajer].[dbo].[Supplier] as suppliers
ON items.SupplierID=suppliers.ID
where "+whereQuery; //I tried with txtQuery.text as well it doesn't work
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = query;
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
//SqlDataReader rd = cmd.ExecuteReader();
//ASPxGridView1.Columns.Clear();
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
}
}
protected string getWhereQuery()
{
string query = txtQuery.Text;
return query;
}
By default (at first page load) you txtQuery.Text is empty, change your getWhereQuery to:
protected string getWhereQuery()
{
string query = txtQuery.Text;
if(string.IsNullOrEmpty(query))
query=" 1=1";
return query;
}