Search code examples
c#datatabledatatable.select

c# DataTable select not working with special characters #


I have a datatable select like:

productData.Select("Name = 'AAA BBB # CCC'");

I know the entry is there, it just doesn't work because of the # character. I have tried escaping with [] like:

productData.Select("Name = 'AAA BBB [#] CCC'");

but it still doesn't work. I know for single quotes I double them so ' becomes ''. But what other characters do I need to be concerned with and how to get this case to work.


Solution

  • Do you absolutely have to use DataTables like this? I've always been incredibly nervous of the text-based querying in DataTable for precisely this reason.

    If at all possible, I suggest you start using LINQ. You can do that with DataTable already, e.g.

    var query = products.AsEnumerable()
                        .Where(row => row.Field<string>("Name") == "AAA BBB # CCC");
    

    That way you don't need to worry about escaping etc. If you use a strongly-typed dataset it becomes even simpler, as you can refer to properties directly instead of using string names.