0

So I have some simple code:

source.Filter = "n LIKE '%" + txtSearch.Text + "%'";

Source being a BindingSource object.

txtSearch being a TextBox.

What is the proper method to make sure it will always consider the contents of txtSearch.Text as a string, and not crash every time I type a "(" or a number of other characters (not sure which yet).

Surely there must be a function somewhere to escape all these, or something?

4

3 回答 3

1

刚遇到同样的问题,从http://www.csharp-examples.net/dataview-rowfilter/找到了这个解决方案

public static string EscapeLikeValue(string valueWithoutWildcards)
{
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < valueWithoutWildcards.Length; i++)
  {
     char c = valueWithoutWildcards[i];
     if (c == '*' || c == '%' || c == '[' || c == ']')
       sb.Append("[").Append(c).Append("]");
     else if (c == '\'')
       sb.Append("''");
     else
     sb.Append(c);
   }
   return sb.ToString();
}
于 2014-10-14T14:16:19.630 回答
0

没有内置功能。但是,您仍然可以像这样编写自己的扩展方法:

public static string RemoveSpecialCharacters(this string str)
{
   StringBuilder stringBuilder  = new StringBuilder();
   foreach (char c in str)
    {
      if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
          (c >= 'a' && c <= 'z') || c == '.' || c == '_') 
      {
         stringBuilder.Append(c);
      }
   }
   return stringBuilder.ToString();
}

你的代码将变成

source.Filter = "n LIKE '%" + txtSearch.Text.RemoveSpecialCharacters() + "%'";

笔记:

您可以将该方法重命名为合适的方法。我使用这个名字只是为了你的理解。

于 2013-06-11T15:42:03.610 回答
0

为什么不在原始查询中包含搜索字符串作为参数?我唯一一次使用 BindingSource.Filter 是当我想按我知道存在的数据进行过滤时,即用特定列上的所有可能值填充 CheckedListBox 并允许用户选择要查看的值。

另一种方法是从特殊字符中捕获异常并通过向用户发送消息来处理它。

于 2013-06-11T16:16:12.230 回答