如何在asp.net中获取Page_init方法中的文本框值?

How to get text box value in Page_init method in asp.net?

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

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

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

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

System.Data.SqlClient.SqlException: Incorrect syntax near 'where'.

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

这是我的代码

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

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

protected string getWhereQuery()
{
    string query = txtQuery.Text;
    if(string.IsNullOrEmpty(query))
     query=" 1=1";
    return query;
}