c#使用ComboBox和Textbox进行搜索 [英] c# Search using ComboBox and Textbox

查看:700
本文介绍了c#使用ComboBox和Textbox进行搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码的问题。每次我在 TextBox 中键入文本时,会发生这种情况。有一个已添加的列及其空(我要删除此列)

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)

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

        }


    }


推荐答案

首先,为什么不使用格式而不是combersome switch ?接下来,不要
在查询中使用 * ,只需枚举您真正想要的所有列:

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

这篇关于c#使用ComboBox和Textbox进行搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆