C#组合框在键入文本时更改所选项目
本文关键字:选项 项目 文本 组合 | 更新日期: 2023-09-27 18:00:46
我有一个组合框。cmbx里面有几百个项目。用户必须能够在cmbx中键入文本。当用户键入文本时,必须选择以键入的值开头的项。用户必须能够继续键入。
我尝试了以下代码:
private void cmbGageCode_TextChanged(object sender, EventArgs e)
{
int itemsIndex = 0;
foreach (string item in cmbGageCode.Items)
{
if (item.Contains(cmbGageCode.Text))
{
cmbGageCode.SelectedIndex = itemsIndex;
}
itemsIndex++;
}
}
这会导致以下结果:当用户在cmbx中键入时,会选择包含该值的项目,并将光标放在文本的前面。这意味着,每当插入2个字符时,就会选择一个项目,并且我无法键入完整的值。
有人知道怎么做吗?也许我需要使用不同的控件?或者也许我做这件事的方式完全错了?请帮忙!
AutoCompleteMode
设置为SuggestAppend
,AutoCompleteSource
设置为ListItems
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.autocompletesource.aspx
试试这个代码。
private void cmbGageCode_TextChanged(object sender, EventArgs e)
{
int itemsIndex = 0;
foreach (string item in cmbGageCode.Items)
{
if (item.IndexOf(cmbGageCode.Text) == 0)
{
cmbGageCode.SelectedIndex = itemsIndex;
cmbGageCode.Select(cmbGageCode.Text.Length - 1, 0);
break;
}
itemsIndex++;
}
}
如果这是你想要的,请告诉我。
有一个内置的auto-complete
支持,您可以执行
ComboBox cmbBox = new ComboBox();
cmbBox.Items.AddRange(new string[] { "aaa", "bbbb", "dddd"});
AutoCompleteStringCollection autoCompleteSource= new AutoCompleteStringCollection();
cmbBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
foreach (string tempStr in cmbBox.Items)
autoCompleteSource.Add(tempStr);
cmbBox.AutoCompleteCustomSource = autoCompleteSource;
cmbBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
this.Controls.Add(cmbBox);//adding combobox to form control collection
首先,在回答Cody Gray时,我需要这个对话框的原因是我的对话框在一个不是STA的应用程序中使用,我无法使其成为STA。自动完成似乎需要STA。所以,我需要自己做。我对Skintkingle的回复做了一些改进,效果很好。
private void CB_TextChanged(object sender, EventArgs e)
{
try
{
CB.TextChanged -= CB_TextChanged; // Don't respond to text changes from within this function
int start = CB.SelectionStart; // Where did user enter new text?
int length = CB.SelectionLength; // How much text did they enter?
if (start > 0) length += start; // Always consider text from beginning of string
string text = CB.Text.Substring(0, length); // Look at start of text
foreach (string item in CB.Items)
{
if (item.StartsWith(text, StringComparison.OrdinalIgnoreCase))
{
// If the typed text matches one of the items in the list, use that item
// Highlight the text BEYOND where the user typed, to the end of the string
// That way, they can keep on typing, replacing text that they have not gotten to yet
CB.Text = item;
CB.SelectionStart = length;
CB.SelectionLength = item.Length - length;
break;
}
}
}
finally
{
CB.TextChanged += CB_TextChanged; // Restore ability to respond to text changes
}
}