【问题标题】:ComboBox DropDownList searching for textComboBox DropDownList 搜索文本
【发布时间】:2016-07-12 22:07:13
【问题描述】:

我有一个ComboBox DataSource 属性设置为这个Type 的列表:

public class ListInfo
{
    public int Key { get; set; }
    public string Name { get; set; }
}

DropDownStyle 设置为DropDownList,我将AutoCompleteSource 设置为ListItemsAutoCompleteMode 设置为SuggestAppend

经过一些测试,客户端返回并要求能够找到文本值的任何部分,而不仅仅是从文本的开头。当DropDownStyle 设置为DropDown 时,我看到的大多数示例都会这样做,但我不能这样做,因为用户无法编辑列表的内容,只需选择一个值。

我尝试创建一个CustomSource,但是当我尝试将AutoCompleteMode 设置为任何值时,我收到以下消息:

当 DropDownStyle 为时,只能使用值 AutoCompleteMode.None ComboBoxStyle.DropDownList 和 AutoCompleteSource 不是 AutoCompleteSource.ListItems。

我找到了这个AutoSuggestCombo,但我又遇到了DropDownStyle 的问题。

我该怎么做:

  1. 使用ComboBox 并将DropDownStyle 设置为DropDown,不允许最终用户输入新元素?

  2. 能够搜索ItemsString 值的任何部分,而不仅仅是DropDownList 样式中当前使用的StartsWith

这是开始使用 Rx 的机会,还是这条路线是一个臃肿的解决方案和随之而来的学习曲线? (到目前为止使用的简单教程)

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    您必须将所有 Autocompletion 属性设置为 none 并自己处理这些内容。 可能有更简单的解决方案,但您可以像这样编写 KeyPress 事件。

    private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        SortedDictionary<int, ListInfo> dict = new SortedDictionary<int, ListInfo>();
    
        int found = -1;
        int current = comboBox1.SelectedIndex;
    
        // collect all items that match:
        for (int i = 0; i < comboBox1.Items.Count; i++)
            if (((ListInfo)comboBox1.Items[i]).Name.ToLower().IndexOf(e.KeyChar.ToString().ToLower()) >= 0)
            // case sensitive version:
            // if (((ListInfo)comboBox1.Items[i]).Name.IndexOf(e.KeyChar.ToString()) >= 0)
                    dict.Add(i, (ListInfo)comboBox1.Items[i]);
    
        // find the one after the current position:
        foreach (KeyValuePair<int, ListInfo> kv in dict)
                 if (kv.Key > current) { found = kv.Key; break; }
    
        // or take the first one:
        if (dict.Keys.Count > 0 && found < 0) found = dict.Keys.First();
    
        if (found >= 0) comboBox1.SelectedIndex = found;
    
        e.Handled = true;
    
    }
    

    您可以决定是否区分大小写;应该不会吧。。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      相关资源
      最近更新 更多