Correct way to escape characters in a DataTable Filter Expression

前端 未结 3 1167
清酒与你
清酒与你 2020-12-01 06:51

I would like to know if there is a function to correctly escape string literals for filter expressions. e.g.:

DataTable.Select(String.Format("[name] = \'         


        
3条回答
  •  清歌不尽
    2020-12-01 07:02

       /// 
        /// If a pattern in a LIKE clause contains any of these special characters * % [ ], those characters must be escaped in brackets [ ] like this [*], [%], [[] or []].
        /// If the pattern is not in a like clause then you can pass valueIsForLIKEcomparison = false to not escape brackets.
        /// Examples:
        /// - strFilter = "[Something] LIKE '%" + DataTableHelper.EscapeLikeValue(filterValue) + "%'";
        /// 
        /// http://www.csharp-examples.net/dataview-rowfilter/
        /// 
        /// LIKE filterValue. This should not be the entire filter string... just the part that is being compared.
        /// Whether or not the filterValue is being used in a LIKE comparison.
        /// 
        public static string EscapeFilterValue(string filterValue, bool valueIsForLIKEcomparison = true)
        {
            string lb = "~~LeftBracket~~";
            string rb = "~~RightBracket~~";
            filterValue = filterValue.Replace("[", lb).Replace("]", rb).Replace("​*", "[*​]").Replace("%", "[%]").Replace("'", "''");
            if (valueIsForLIKEcomparison)
            {
                filterValue = filterValue.Replace(lb, "[[]").Replace(rb, "[]]");
            }
            else
            {
                filterValue = filterValue.Replace(lb, "[").Replace(rb, "]");
            }
    
            return filterValue;
        }
    

提交回复
热议问题