c# DataTable.cselect(string regExpression) strange exception throwing

I am developing a c# database program but now I have trouble using the DataTable's Select(string regExpression) method.

I am calling the method like that:

DataRow[] tmpDr = tblUser.Select("user_id=JonDoe");

Always when I try to do that, the Select method throws an exception "The column [JonDoe] was not found. "

But my understanding of the Select method was that in my case it selects all rows from tblUser where user_id=JonDoe. So user_id is the column and JonDoe the value I am looking for. Why is the Select function assuming that JonDoe would be a column in a table?

Thank you for all your answers!

Jon Skeet
people
quotationmark

You should read the DataTable.Expression documentation. In particular:

User-defined values may be used within expressions to be compared with column values. String values should be enclosed within single quotation marks (and each single quotation character in a string value has to be escaped by prepending it with another single quotation character).

So in this case you want:

DataRow[] tmpDr = tblUser.Select("user_id='JonDoe'");

You're currently not specifying the value in quotes, so it's being treated as a reference to a column - just like it would be in SQL.

Obviously this sort of approach is vulnerable to the same sort of injection attacks as SQL... but without the mitigating feature of parameterized queries, as far as I'm aware. If you want to filter on user-specified values that might include quotes etc, you might be better off to use LINQ, e.g.

var rows = tblUser.AsEnumerable().Where(x => x.Field<string>("user_id") == userId);

people

See more on this question at Stackoverflow