簡體   English   中英

使用ComboBox和Textbox進行c#搜索

[英]c# Search using ComboBox and Textbox

我對此代碼有疑問。 每次我在TextBox鍵入文本時,都會發生這種情況。 有一個添加的列,它是空的(我想刪除它)

在此處輸入圖片說明

    public void searchData()
    {

        string sql = "Select * from Inventory";
        cmd = new OleDbCommand(sql, con);

        try
        {
            con.Open();
            cmd.Connection.CreateCommand();
            string value = cboFields.Text;
            switch (value)
            {
                case "ID":
                    cmd.CommandText = "Select * from Inventory where ID LIKE @searchKey";
                    break;
                case "Quantity":
                    cmd.CommandText = "Select * from Inventory where Quantity LIKE @searchKey";
                    break;
                case "Unit":
                    cmd.CommandText = "Select * from Inventory where Unit LIKE @searchKey";
                    break;
                case "ItemCode":
                    cmd.CommandText = "Select * from Inventory where ItemCode LIKE @searchKey";
                    break;
                case "ItemName":
                    cmd.CommandText = "Select * from Inventory where ItemName LIKE @searchKey";
                    break;
                case "Cbm":
                    cmd.CommandText = "Select * from Inventory where Cbm LIKE @searchKey";
                    break;
                case "TotalCbm":
                    cmd.CommandText = "Select * from Inventory where TotalCbm LIKE @searchKey";
                    break;
                case "":
                    cmd.CommandText = "Select * from Inventory";
                    MessageBox.Show("Select fields where you want to searchData for");
                    txtSearch.SelectionStart = 0;
                    txtSearch.SelectionLength = txtSearch.Text.Length;
                    break;       
            }

            cmd.Parameters.AddWithValue("@searchKey", "%" + txtSearch.Text.ToString() + "%");
            OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
            adap.Fill(dt);
            DGVinventory.DataSource = dt;


            con.Close();

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();

        }


    }

首先,為什么不使用格式來代替繁瑣的switch呢? 接下來,不要在查詢中使用* ,只需枚舉您真正想要的所有列即可:

  cmd.CommandText = String.Format(
    @"select Id,      
             Quantity,
             Unit --TODO: Add other required columns here
        from Inventory
       where {0} like @searchKey", value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM