【问题标题】:Search in a combo box在组合框中搜索
【发布时间】:2018-12-18 11:11:06
【问题描述】:

我有一个名为cbProduit 的组合框;组合框正在通过网络服务填充:

ComboBoxItemProduit produiItem = new ComboBoxItemProduit();
produiItem.Text = articleArray.GetAllArticlesResult[i].S_MODELE;
produiItem.Value = articleArray.GetAllArticlesResult[i].S_ID;
cbProduit.Items.Add(produiItem);

问题是,组合框在填充时包含超过 30000 个项目,我需要通过文本进行搜索。

注意:我与数据库没有任何关系,所有信息都来自 Web 服务。

有人可以帮忙吗?

【问题讨论】:

  • 你有没有尝试使用组合框的 textchanged 事件?我认为您可以在此事件中过滤数据。
  • 不,我没有使用 Text changed,如果我可以使用,我该如何过滤这些项目?
  • 尝试限制项目数,例如使用附加过滤器。将这么大的项目计入控件并不是一个好习惯。很有可能您不必全部拥有它们。问题是 - 你想按文本过滤项目吗(例如在谷歌中)?如果是这样,那么您需要编辑和动态列表框。
  • 它是一个窗体应用程序
  • 我需要将它们全部列在组合框中,是的,当我在组合中输入内容时,我需要它过滤并只显示我输入的垃圾的项目

标签: c# winforms search combobox


【解决方案1】:

我看到有两个选项符合您的描述。

选项 1

您为组合框设置了一个自动完成属性,如下所示:

comboBox1.DataSource = dt;
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "VALUE";
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;

但是,它只适用于您的第一个字符,并会显示如下列表:

选项 2

放置一个带有 textChanged 事件的新文本框:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        comboBox1.DataSource = dt; //your origin data

    }
    else
    {
        var newTable = dt.AsEnumerable()
      .Where(x => x.Field<string>("VALUE").ToUpper().Contains(textBox1.Text.ToUpper()))
      .CopyToDataTable();

        comboBox1.DataSource = newTable;

    }
}

虽然 dt 是来自服务器的原始数据 结果是这样的:

【讨论】:

    【解决方案2】:

    您可以将组合框的值存储在一个数组中并在该数组中搜索项目。使用以下方法

    //Declare a list of string in the general declarations section of the form as follows
    List<string> liststr = new List<string>();
    //Add this line when populating the combo box
    liststr.Add(produiItem);
    //under the text changed event of the combo box, add these lines of code.
    cbProduit.Items.Clear;
    foreach (string search in liststr)
    {
        if (search.StartsWith(cbProduit.Text)) { 
              cbProduit.Items.Add(search);
    
        }    
    }
    

    【讨论】:

      【解决方案3】:

      试试这个搜索不需要数据库

      <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <p>Use this area to provide additional information.</p> <select id="drop" class="js-example-basic-single"  style="width:200px;">
          <option>Hiii</option>
          <option>I</option>
          <option>Am</option>
          <option>Doing</option>
          <option>Asp</option>
          <option>MVC</option>
      
      </select>
      
      <script>$(document).ready(function () {
          $('.js-example-basic-single').select2();    });
      

      【讨论】:

        猜你喜欢
        • 2013-03-30
        • 2017-11-05
        • 1970-01-01
        • 2016-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多