Asp.net C# - Replace all special characters from string:
"Input string was not in correct format" more or less all the .net programmers facing this issue at least one time in his carrier. Most of the times this issue caused by special characters mingle in data base query and it may entered via input controls. For example single quotes(') in address like "Peter's Road" in that time the SQL query binding with error due to that single quotes.
In this case we need to replace the special characters from the input values that produce this error. In c# the "String.Replace" method used to replace the string values. Here You can replace the user input's special characters by using the following c# method.
Just send your input control value as parameter:
"Input string was not in correct format" more or less all the .net programmers facing this issue at least one time in his carrier. Most of the times this issue caused by special characters mingle in data base query and it may entered via input controls. For example single quotes(') in address like "Peter's Road" in that time the SQL query binding with error due to that single quotes.
In this case we need to replace the special characters from the input values that produce this error. In c# the "String.Replace" method used to replace the string values. Here You can replace the user input's special characters by using the following c# method.
public static string ReplaceSpecialCharacters(string strInput) { strInput = strInput.Replace("--", "++"); strInput = strInput.Replace('&', ','); strInput = strInput.Replace("%", "[%]"); strInput = strInput.Replace('+', ','); strInput = strInput.Replace("_", "[_]"); strInput = strInput.Replace("[", "[[]"); strInput = strInput.Replace("]", "[]]"); strInput = strInput.Replace("'", "''"); return strInput; }
string txtAddress = StringHelper.ReplaceSpecialCharacters(txtAddress.Text.Trim());