[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 652
  • Last Modified:

Datatable Select Method Problem

The C# code shown below performs an operation using two datatables.  dt1 is a master list of customers; dt2 is a list of customers to be excluded from the master list based on the key field “CustID”.   The existing code uses the datatable Select method to identify a matched record in dt2, then it deletes the corresponding record in dt1.  The routine works perfectly UNTIL a record contains a CustID that uses a single quote mark ( ‘ ) in the CustID field.  For example CustID=ACME001 works fine, but CustID=ACME’001 would fail.  I understand why the single quote causes the problem, but I do not know the most efficient means of solving the problem so that regardless of the special characters that might be embedded in the CustID field, the routine will still work as intended.  Any help is much appreciated.
dt1 = GetMasterList();  //contains master customer list
dt2 = GetExclusionList(); //contains list to exclude
for (int i = dt1.Rows.Count - 1; i >= 0; i--)
DataRow[] rows = dt2.Select("CustID='" + dt1.Rows[i]["CustID"].ToString() + "'");
if (rows.Length > 0)

Open in new window

1 Solution
When you are loading the query you can replace the single tick in the field by using the "Replace" Method.
string sQuery = "Select * from table where Name = '" +
                           tbText.Text.Replace("'", "''") +
HainKurtSr. System AnalystCommented:
DataRow[] rows = dt2.Select("CustID='" + dt1.Rows[i]["CustID"].ToString() + "'");
when it is like "Hain'Kurt" select becomes


and it is not valid, so you should replace ' with ''

DataRow[] rows = dt2.Select("CustID='" + dt1.Rows[i]["CustID"].ToString().Replace("'","''") + "'");


which is valid now ('' means one ' in string...)
dev775Author Commented:
HainKurt - this was the exact answer I was looking for.  Thanks!

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now