c# Search using ComboBox and Textbox

2019-09-10 02:45发布

I have a problem with this code. Every time I type a text in the TextBox this happen. there's an added column and its empty(I want to remove this)

enter image description here

    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();

        }


    }

1条回答
该账号已被封号
2楼-- · 2019-09-10 03:29

First, why not use formatting instead of combersome switch? Next, do not use * in the query, just enumerate all the columns you really want:

  cmd.CommandText = String.Format(
    @"select Id,      
             Quantity,
             Unit --TODO: Add other required columns here
        from Inventory
       where {0} like @searchKey", value);
查看更多
登录 后发表回答