DataTable expression Cannot interpret token '!'

最后都变了- 提交于 2019-12-23 12:19:23

问题


I have the following code:

//myDataTable has the following collumns: UserName, Birthday and email.
string name = "eric!";
string expression = "UserName = " + name;
DataRow[] result = myDataTable.Select(expression);

I want to select all rows with the name "eric!".
The "!" gives me the following error:

Cannot interpret token "!".

How can I select all rows with such tokens?
(I really need the "!" in the expression since I extract the userNames from a .sql file)


回答1:


You should use your name between ''. Like;

string name = "'eric!'";

Without single quotes, your DataTable.Select method thinks that ! is an operator and it is not allowed in DataColumn.Expression property as a valid operator.

From documentation;

User-Defined Values

User-defined values may be used within expressions to be compared with column values. String values should be enclosed within single quotation marks.




回答2:


You are missing quotes (' ') around your value

string name = "eric!";
string expression = "UserName = '" + name+'";
DataRow[] result = myDataTable.Select(expression);

When you write the filter operator without quotes and with !, it will consider ! as not operator that's why it gives the error.



来源:https://stackoverflow.com/questions/21645666/datatable-expression-cannot-interpret-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!