基于Microsoft Access的data binding source过滤,点击按钮展示匹配值如何实现
完整实现代码
private void button2_Click(object sender, EventArgs e) { textBox1.Focus(); string inputKeyword = textBox1.Text.Trim(); if (string.IsNullOrEmpty(inputKeyword)) { MessageBox.Show("Please input a word"); return; } // 转义输入中的单引号,避免Filter语法错误 string escapedKeyword = inputKeyword.Replace("'", "''"); // 配置过滤规则:匹配ID转字符串后命中关键词,或Word字段命中关键词 dictBindingSource.Filter = $"(Convert(ID, 'System.String') = '{escapedKeyword}') OR (Word = '{escapedKeyword}')"; // 判断是否有匹配结果 if (dictBindingSource.Count > 0) { // 取匹配结果的对应字段赋值给标签,可替换为你需要展示的字段名 label1.Text = dictBindingSource.Current["Word"].ToString(); } else { MessageBox.Show("Word not found"); label1.Text = string.Empty; } }
规则调整说明
- 代码中的
dictBindingSource请替换为你实际使用的BindingSource控件名称,label1替换为项目里的标签控件名称 - 如果需要模糊匹配(只要包含输入关键词就算命中),可以把过滤条件里的
=改成LIKE,并在关键词前后加通配符:dictBindingSource.Filter = $"(Convert(ID, 'System.String') LIKE '%{escapedKeyword}%') OR (Word LIKE '%{escapedKeyword}%')"; - 原参考代码中的
Sysem.String为拼写错误,已修正为System.String - 如果你的ID字段本身就是字符串类型,可以去掉Convert转换逻辑,直接写
ID = '{escapedKeyword}'即可
内容的提问来源于stack exchange,提问作者Wai Yan Oo
相关产品推荐
相关产品推荐

