[英]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.