Skip to content Skip to sidebar Skip to footer

.net Framework Datatable.select(string) Method When The Filter Expression Contains ' Or "

In a .Net web application I use the public DataRow[] Select(string filterExpression) method in many places. Due to a last minute change characters such as ' and ' are now valid in

Solution 1:

Escape the single quote (') in an expression literal by doubling it: ''

No need to escape the double quote (") within a string literal. String literals are bound by single quotes, so the double quote need only be standard C# escaped: \" (or "" if within a verbatim string starting with the @ symbol)

See this link for more information.

Solution 2:

Escape the single quote ' by doubling it to ''. Escape * % [ ] characters by wrapping in []. e.g.

privatestringEscapeLikeValue(stringvalue)
{
    StringBuilder sb = new StringBuilder(value.Length);
    for (int i = 0; i < value.Length; i++)
    {
        char c = value[i];
        switch (c)
        {
            case']':
            case'[':
            case'%':
            case'*':
                sb.Append("[").Append(c).Append("]");
                break;
            case'\'':
                sb.Append("''");
                break;
            default:
                sb.Append(c);
                break;
        }
    }
    return sb.ToString();
}

public DataRow[] SearchTheDataTable(string searchText)
{ 
     return myDataTable.Select("someColumn LIKE '" 
                                 + EscapeLikeValue(searchText) + "'");
} 

Thanks to examples here

Post a Comment for ".net Framework Datatable.select(string) Method When The Filter Expression Contains ' Or ""