Set all quotes to double quote using C#

148 views Asked by At

I try to make it possible for users to search for customers with a quote in the CustomerName.

The user search the user in the customerNameTextBox wich is set to the customerNameTB.

If the user uses a quote(') it will be replaced with a double-quote.

And if there is a triple quote(''') it will be replaced with a double-quote.

Here is my code:

string customerNameTB = customerNameTextbox.Text;                
customerNameTB.Replace("'", "''");                
while (customerNameTB.Contains("'''"))
{
   customerNameTB.Replace("'''", "''");
}

The result after this code is the quotes are still single quotes.

Whats is wrong with this little piece of code..

Edit after answers

My code should look like this:

 string customerNameTB = customerNameTextbox.Text;                
    customerNameTB = customerNameTB.Replace("'", "''");                
    while (customerNameTB.Contains("'''"))
    {
       customerNameTB = customerNameTB.Replace("'''", "''");
    }
2

There are 2 answers

3
bkribbs On BEST ANSWER

You're close! This is what you need:

string customerNameTB = customerNameTextbox.Text;  
// single quotes
customerNameTB = customerNameTB.Replace("'", "''");
// triple quotes
customerNameTB = customerNameTB.Replace("'''", "''");

The replace doesn't replace it in the original string, it returns a new string that you have to assign to something or it just gets thrown away.

1
Denis  Yarkovoy On

String.Replace does not modify the string it is running on. You need to assign the result of Replace to your string:

   string customerNameTB = customerNameTextbox.Text;                
   customerNameTB=customerNameTB.Replace("'", "''");                
   customerNameTB=customerNameTB.Replace("'''", "''");

Also, there is no need for a loop, since Replace replaces ALL occurrences of the search string.