1

这是我的情况。我想执行分页、分组和过滤。所以我正在使用 page_init 方法。根据我的代码,它工作正常。但用户只能给出 where 子句条件,如

例如,我的页面中有一个文本框。那个文本框ID="txtQuery",在那个文本框中,用户将输入 where 子句,itemID='45366'所以我必须使我的代码如下所示

cmd.commandText="select * from TABLE_NAME where "+txtQuery.text

所以这将显示记录。这就是现在的问题。当我cmd.commandText像上面那样做时,它会抛出一个错误

System.Data.SqlClient.SqlException:“位置”附近的语法不正确。

如果我直接给,它工作正常,没有任何错误。

这是我的代码

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;
}
4

1 回答 1

2

默认情况下(在第一页加载)你 txtQuery.Text 是空的,将你的 getWhereQuery 更改为:

protected string getWhereQuery()
{
    string query = txtQuery.Text;
    if(string.IsNullOrEmpty(query))
     query=" 1=1";
    return query;
}
于 2016-12-19T11:34:36.460 回答