C#:Remove Special Characters from Text box in ASP.Net | Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more

C#:Remove Special Characters from Text box in ASP.Net


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.

        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;
Just send your input control value as parameter:
string txtAddress = StringHelper.ReplaceSpecialCharacters(txtAddress.Text.Trim());


Amazing blog and very interesting stuff you got here! I definitely learned a lot from reading through some of your earlier posts as well and decided to drop a comment on this one!

Post a Comment

Share your thoughts here...




Blogger Widgets