DataTable select method with single quote conflict C#

烂漫一生 提交于 2019-11-27 06:52:24

问题


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?


回答1:


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




回答2:


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




回答3:


You can try the following code:

string Name = EscapeSpecialCharacters(drData["Name"].ToString());

DataRow[] newDr = this.ds.Tables["TableName"].Select("Name = '" + Name  + "'");
private static string EscapeSpecialCharacters(string Name)
{
   StringBuilder sb = new StringBuilder(Name.Length);
   for (int i = 0; i < Name.Length; i++)
   {
        char c = Name[i];
        switch (c)
        {
                case ']':
                case '[':
                case '%':
                case '*':
                    sb.Append("[" + c + "]");
                    break;
                case '\'':
                    sb.Append("''");
                    break;
                default:
                    sb.Append(c);
                    break;
        }
   }
   return sb.ToString();
}


来源:https://stackoverflow.com/questions/18663605/datatable-select-method-with-single-quote-conflict-c-sharp

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