单引号冲突的DataTable选择方法C# [英] DataTable select method with single quote conflict C#

查看:28
本文介绍了单引号冲突的DataTable选择方法C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现当我在包含撇号的字段下执行 LINQ 选择时,它使我的应用程序抛出异常.

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() + "'");

如果 drData["Name"] = "公司的钱"

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

出现语法错误:'S' 运算符后缺少操作数"

谁能告诉我如何保存它,不要更换或删除它,好吗?

推荐答案

你必须将单引号转义为 2 个单引号,可能还有其他特殊字符,所以你必须照顾它们:

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("'","''")));

有关在过滤器字符串中转义特殊字符的更多示例(在 Select 方法中使用):行过滤字符串示例

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

这篇关于单引号冲突的DataTable选择方法C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆