문제

I recently found when I do a LINQ select under a field that contains an apostrophe, it makes my application to throw an exception.

DataRow[] newDr = this.ds.Tables["TableName"].Select("Name = '" + drData["Name"].ToString() + "'");

If drData["Name"] = "The business's money"

I got an exception of "Syntax error: Missing operand after 'S' operator "

Can anyone tell me how to preserve it and no replace it or remove it, please?

도움이 되었습니까?

해결책

You have to escape the single quote to 2 single quotes, there may be other special characters so you have to take care of them:

DataRow[] newDr = this.ds.Tables["TableName"]
                         .Select(string.Format("Name ='{0}'",drData["Name"].ToString().Replace("'","''")));

More examples on escaping special characters in a filter string (used in Select method): Row filter string examples

다른 팁

Its Not LINQ Select, instead its DataTable.Select method. The error you are getting is because of character ', you need to escape it with double ' '. Simple way would be to replace it like:

DataRow[] newDr = this.ds.Tables["TableName"]
                     .Select("Name = '" + drData["Name"].ToString().Replace("'", "''" + "'");

You may see this question for how to escape characters in DataTable.Select

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top