繁体   English   中英

组合框上的自动完成限制

[英]Restricted autocompletion on combobox

我有一个组合框,我也不想让用户也添加新数据,但我也想让他们键入要选择的对象的标题。

目前,我正在使用此代码:

    protected virtual void comboBoxAutoComplete_KeyPress(object sender, KeyPressEventArgs e) {
        if (Char.IsControl(e.KeyChar)) {
            //let it go if it's a control char such as escape, tab, backspace, enter...
            return;
        }
        ComboBox box = ((ComboBox)sender);

        //must get the selected portion only. Otherwise, we append the e.KeyChar to the AutoSuggested value (i.e. we'd never get anywhere)
        string nonSelected = box.Text.Substring(0, box.Text.Length - box.SelectionLength);

        string text = nonSelected + e.KeyChar;
        bool matched = false;
        for (int i = 0; i < box.Items.Count; i++) {
            if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().StartsWith(text, true, null)) {
                //box.SelectedItem = box.Items[i];
                matched = true;
                break;
            }
        }

        //toggle the matched bool because if we set handled to true, it precent's input, and we don't want to prevent
        //input if it's matched.
        e.Handled = !matched;
    }

它适用于使用绑定到数据库的数据的任何组合框,并且不区分大小写。 但是,如果用户在错误的情况下输入了某些内容,然后在组合框中使用了制表符,则组合框的选定值仍为-1(或先前的值)。 那不是我想要的行为,我希望它将值设置为当前最能猜出用户正在绑扎什么的值,即自动完成选项。

如果您在for循环中看到注释掉的行,我已经尝试过了。 那不行
它执行以下操作:
我的字段“租金”的值为53
我输入“ r”
我得到的结果是“ rRent”
combobox.SelectedValue返回-1

目前的功能:
我的字段“租金”的值为53
我输入“ r”
自动完成提示“租金”
这是正确的值,所以我继续前进,组合框失去了焦点
组合框显示“租金”
combobox.SelectedValue返回-1

我想要的是:
我的字段“租金”的值为53
我输入“ r”
组合框失去焦点,而是填写“租金”(即使不是在正确的情况下[已经这样做])
combobox.SelectedValue现在应该返回53

我认为设置box.SelectedValue可能会更好,但我不知道如何做到这一点,至少以一种高级抽象的方式,如果我知道组合框是如何用ValueMemeber和Display成员做到的,我会复制它,但是我不知道“T。

有人对如何解决此错误有任何建议吗?

可能是树错了,但是您是否尝试过仅在组合框上启用自动完成功能?

comboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;        

最后一行将限制输入到列表中的项目。

看来我别无选择,只能在LeaveFocus事件中执行此操作,这可以解决问题:

    protected void autocomplete_LeaveFocus(object sender, EventArgs e) {
        ComboBox box = ((ComboBox)sender);
        String selectedValueText = box.Text;

        //search and locate the selected value case insensitivly and set it as the selected value
        for (int i = 0; i < box.Items.Count; i++) {
            if (((DataRowView)box.Items[i])[box.DisplayMember].ToString().Equals(selectedValueText, StringComparison.InvariantCultureIgnoreCase)) {
                box.SelectedItem = box.Items[i];
                break;
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM