tags:

views:

1318

answers:

2

Hi

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] = '{0}'", MyName))

If MyName contains ' or a number of other key characters an exception is generated. The Microsoft documentation indicates that these charaters should be correctly escaped, however there is a bit of confusion on how this is to be done.

I have tried replacing ' with \' and also ['] as indicated in the documentation, however the query still fails.

Many Thanks

+1  A: 

Balls. Might help if I read the comments of the article I cited!

If I replace ' with two single ' the query works.

Ady
That's not even DataTable specific, but rather the general way of doing it in SQL. :-)
Tomalak
Although I use parameterised queries, so don't come across the need for this in SQL. But I get you.
Ady
If you use parameterized queries you are on the safe side anyway, but a TableFilter is an in-memory subset of SQL, consisting of a WHERE clause that must conform to SQL syntax rules. It's just a string, so no parameters here. That's why this extra step must be taken.
Tomalak
+1  A: 

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

private string EscapeLikeValue(string value)
{
    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

Rory