combox输入文字进行自动匹配代码
时间: 2023-07-09 18:37:40 浏览: 71
以下是一个简单的C#示例代码:
```csharp
private void Form1_Load(object sender, EventArgs e)
{
// 添加下拉列表项
comboBox1.Items.Add("apple");
comboBox1.Items.Add("banana");
comboBox1.Items.Add("cherry");
comboBox1.Items.Add("grape");
comboBox1.Items.Add("orange");
// 设置自动匹配模式为SuggestAppend,来源为ListItems
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
// 遍历下拉列表项,查找匹配项
string userInput = comboBox1.Text;
foreach (string item in comboBox1.Items)
{
if (item.StartsWith(userInput, StringComparison.CurrentCultureIgnoreCase))
{
// 如果找到匹配项,设置combox的Text属性为匹配项文本
comboBox1.Text = item;
comboBox1.SelectionStart = userInput.Length;
comboBox1.SelectionLength = item.Length - userInput.Length;
return;
}
}
// 如果没有找到匹配项,显示提示信息
label1.Text = "No matching item found.";
}
private void comboBox1_Leave(object sender, EventArgs e)
{
// 在combox失去焦点时,重置Text属性
comboBox1.Text = "";
}
```
在上述代码中,我们在窗体加载时添加了一些下拉列表项,同时设置了combox的自动匹配模式和来源。在TextChanged事件中,我们遍历了下拉列表项,查找是否有以用户输入的文字开头的匹配项,如果找到匹配项,就设置combox的Text属性为匹配项的文本,同时选中匹配项中用户输入的部分。如果没有找到匹配项,就在label1中显示一条提示信息。在combox失去焦点时,我们重置了combox的Text属性,以便下次使用时重新开始匹配。