Posts Tagged ‘ sqlstring ’

Tackling Apostrophes in SQL String with C#

Apostrophes always screws up SQL string that contains inputs from user. The easiest way to deal with this is to checkout each string input from user and replace single apostrophes with two apostrophes.

Utility.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ApostrphesTrial
{
public static class Utility
{
public static string EscapeApostrophes(string input)
{
return input.Replace("'", "''");
}
}
}

Use this “EscapeApostrophes” Method each time with user input (string) to create a SQL string for database interaction.

string userName = Utility.EscapeApostrophes(userNameTextBox.Text);

Thanks
A Rahim Khan