【问题标题】:c# Search using ComboBox and Textboxc# 使用组合框和文本框进行搜索
【发布时间】:2016-01-20 06:33:20
【问题描述】:

我对这段代码有疑问。每次我在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();

        }


    }

【问题讨论】:

    标签: c# search combobox textbox


    【解决方案1】:

    首先,为什么不使用 formatting 来代替复杂的switch?接下来,不要 在查询中使用*,只需枚举您真正想要的所有列:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多