使用网页上的多个字段搜索MS ACCESS数据库-c#

时间:2018-10-27 06:26:08

标签: c#

我有一个包含多个文本框和列表框的搜索页面。我想基于一个或多个字段进行搜索。

我正在连接到MS ACCESS数据库并在gridview上显示。

下面是我的代码。

我在if else语句中添加每个条件,但是如果不可能,则我会添加所有条件。

那么还有什么更好的方法吗?

Private DataTable getDataTable()
    {
        OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Project.accdb");
        string query;
        OleDbCommand cmd;
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        //Open the connection to db
        con.Open();

        var Merchant_ID = txt_MrchntID.Text;
        var Chain_ID = txt_ChnID.Text;
        var Reason_Code = txt_Reason.Text;
        var Date_From = Text_Date_From.Text;
        var Date_To = Text_Date_To;
        var Amt_From = txt_Amount_From.Text;
        var Amt_To = txt_Amount_To.Text;
        var Status = SELECT_Status.Text;
        var Tran_Type = Select_Trans_Type.Text;
        //Search by only Merchant ID.
        if (Merchant_ID.Length > 0 && Chain_ID == "" && Reason_Code =="" && Date_From== "" && Amt_From =="" && Status == "SELECT" && Tran_Type == "SELECT")
        {
            //Generating the query to fetch data

            query = @"select * from table where I_MRCHNT = '" + txt_MrchntID.Text + "' ";

            //cmd = new OleDbCommand(query, con);


            adapter.SelectCommand = new OleDbCommand(query, con); 
            adapter.Fill(ds);
            con.Close();


        }
        // Search by Merchant ID and Chain ID together.
        else if (Merchant_ID.Length > 0 && Chain_ID.Length > 0 && Reason_Code == "" && Date_From == "" && Amt_From == "" && Status == "SELECT" && Tran_Type == "SELECT")
        {

            //Generating the query to fetch data
            query = @"select * from table where I_MRCHNT = '" + txt_MrchntID.Text + "' and I_CHN = '" + txt_ChnID.Text + "' ";

            cmd = new OleDbCommand(query, con);
            adapter.SelectCommand = new OleDbCommand(query, con);
            adapter.Fill(ds);
            con.Close();


        }

        return ds.Tables[0];
    }

0 个答案:

没有答案