How to solve issue of single quote in filer value using DataTable.Select()

后端 未结 3 944
慢半拍i
慢半拍i 2021-01-22 05:18

Assuming I want productCode variable below to be assigned the product code of a product named Cookie\'s

NOTE the \"\'\" in the the Prod

相关标签:
3条回答
  • 2021-01-22 05:31

    Use LINQ, this will make your solution simplier and more general. Otherwise you will end up with replacing single quotes (and other special characters) in the filter with escape chars.

    DataTable dt=PullSomeDataFromProductTableDatabase();
    string filterValue="Cookie's";
    string productCode=dt.AsEnumerable()
                         .Where(row => row.Field<string>("ProductName") == filterValue)
                         .FirstOrDefault(row => row.Field<string>("ProductCode"));
    
    0 讨论(0)
  • 2021-01-22 05:34

    Double up any single quotes like this

    ...dt.Select("[ProductName] = '" + filterValue.Replace("'", "''") + "'")[0]["ProductCode"]
    
    0 讨论(0)
  • 2021-01-22 05:38

    Try string filterValue="Cookie''s";

    or

    string filterValue="Cookie'+CHAR(39)+'s";

    0 讨论(0)
提交回复
热议问题