实现TextBox自动补全:基于List<string>支持姓名/手机号模糊搜索
实现支持姓名/手机号任意位置匹配的TextBox自动补全
核心思路
- 先解析列表中每个字符串的姓名和手机号字段,避免直接对整串模糊匹配导致ID部分误匹配
- 监听TextBox输入变化事件,实时过滤包含输入文本的姓名或手机号条目
- 利用字符串任意位置匹配逻辑,同时支持大小写不敏感匹配
具体实现代码
1. 编写匹配判断辅助方法
private bool IsCustomerMatch(string customerEntry, string inputText) { // 按固定分隔符分割条目,处理前后空格 string[] entryParts = customerEntry.Split(new[] { " | " }, StringSplitOptions.None); if (entryParts.Length != 3) return false; // 跳过格式错误的条目 string customerName = entryParts[1].Trim(); string customerPhone = entryParts[2].Trim(); // 大小写不敏感的任意位置匹配 return customerName.IndexOf(inputText, StringComparison.OrdinalIgnoreCase) >= 0 || customerPhone.IndexOf(inputText, StringComparison.OrdinalIgnoreCase) >= 0; }
2. 绑定TextBox输入事件(以WinForms为例)
在TextBox的TextChanged事件中执行过滤并更新自动补全源:
private void CustomerTextBox_TextChanged(object sender, EventArgs e) { string inputContent = CustomerTextBox.Text.Trim(); if (string.IsNullOrEmpty(inputContent)) { // 输入为空时清空补全列表或恢复全部条目 CustomerTextBox.AutoCompleteCustomSource.Clear(); return; } // 过滤符合条件的条目 var matchedCustomers = custList.Where(item => IsCustomerMatch(item, inputContent)).ToList(); // 更新自动补全数据源 CustomerTextBox.AutoCompleteCustomSource.Clear(); CustomerTextBox.AutoCompleteCustomSource.AddRange(matchedCustomers.ToArray()); }
3. 初始化TextBox自动补全配置
在窗体加载时配置自动补全基础属性:
private void Form_Load(object sender, EventArgs e) { // 设置自动补全模式和来源 CustomerTextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; CustomerTextBox.AutoCompleteSource = AutoCompleteSource.CustomSource; // 初始加载全部客户条目 CustomerTextBox.AutoCompleteCustomSource.AddRange(custList.ToArray()); }
关键细节说明
- 使用
" | "作为分割符,避免因姓名中的空格导致分割错误 - 用
String.IndexOf配合StringComparison.OrdinalIgnoreCase实现大小写不敏感的模糊匹配,比Contains重载更直观 - 如果是WPF项目,逻辑类似:监听
TextBox.TextChanged事件,过滤结果后绑定到AutoCompleteBox或ComboBox的ItemsSource
内容的提问来源于stack exchange,提问作者محمد السروجي
相关产品推荐
相关产品推荐

