Link to home
Start Free TrialLog in
Avatar of dev775
dev775

asked on

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)
dt1.Rows.Remove(dt1.Rows[i]);
}

Open in new window

Avatar of Only1RB
Only1RB

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("'", "''") +
                           "'";
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dev775

ASKER

HainKurt - this was the exact answer I was looking for.  Thanks!