1
votes

I am getting below error in my code:

Missing operand after 'L' operator.

I debugged the code and found that it is occurring in below line:

DataRow[] documents = this.DataSet.Results_Documents.Select(String.Format("DocumentControlNumber = '{0}'", dcn), null, DataViewRowState.CurrentRows);

Here it is occurring when dcn contains ' in its full string.

What is the exact reason for this?

For example: dcn :- Nat'l Bk of Sheldon

2
Sample values for dcn?? - Sujeet Sinha
Why would a document number contain an apostrophe? Do you need to replace the single quote with two singe quotes to escape it? - D Stanley

2 Answers

6
votes

Here it is occurring when dcn contains ' in its full string.

Yup; a common problem with using concatenation; let's use the example dcn as Nat'l Bk of Sheldon from you question; the query is now:

DocumentControlNumber = 'Nat'l Bk of Sheldon'

which is malformed. Since this doesn't allow proper parameterization, you will need to "escape" the value; If I had to guess, to one of:

DocumentControlNumber = 'Nat''l Bk of Sheldon'

or

DocumentControlNumber = 'Nat\'l Bk of Sheldon'

(noting that the \ n C# also needs escaping, or use of verbatim string literals)

Either should be achievable via a string.Replace; for example dcn.Replace("'","''") (in the parameter to string.Format).

2
votes

The Select requires the string to be in a specific format, when you have a ' the string is no longer valid. You need to escape quotes by repacing every ' with ''

DataRow[] documents = this.DataSet.Results_Documents.Select(
                            String.Format("DocumentControlNumber = '{0}'"
                                         , dcn.ToString().Replace("'", "''")
                            ), null, DataViewRowState.CurrentRows);

if dcn is a string you don't need the .ToString()