我有一个组合框,我不希望用户也添加新数据,但我也想让他们输入他们想要选择的对象的标题。
目前我正在使用此代码:
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;
}
它适用于任何使用绑定(bind)到数据库的数据的组合框,并且不区分大小写。但是,如果用户输入了错误的大小写,然后按 Tab 键退出组合框,则组合框的选定值仍为 -1(或之前的值)。这不是我想要的行为,我希望它将值设置为当前对用户绑定(bind)内容的最佳猜测,即自动完成选项。
我已经尝试过了,如果您在 for 循环中看到注释掉的行。那是行不通的。
它做了这样的事情:
我的“租金”字段值为 53
我输入“r”
我得到结果“rRent”
combobox.SelectedValue 返回 -1
目前的用途:
我的“租金”字段值为 53
我输入“r”
自动完成建议“租金”
这是正确的值,所以我继续,组合框失去焦点
组合框显示“租金”
组合框.SelectedValue返回-1
我想要什么:
我的“租金”字段值为 53
我输入“r”
组合框失去焦点,它填充“租金”(即使它的大小写不正确[已经这样做了])
combobox.SelectedValue 现在应该返回 53
我认为设置 box.SelectedValue 可能会更好,但我不知道如何做到这一点,至少以高级抽象的方式,如果我知道组合框如何使用 ValueMemeber 和 Display 成员做到这一点,我会复制它但我不这么认为。
有人对如何解决此错误有任何建议吗?
最佳答案
可能是找错了树,但是您是否尝试过在组合框上启用自动完成功能?
comboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
最后一行将限制对列表中项目的输入。
关于c# - 组合框上的限制自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/868632/