Thursday, August 24, 2017 : How to remove special character’s from string

In this article I am going to explain how to remove special character’s from string or  text typed/entered in Textbox in

I want to remove special characters from text typed/entered in Textbox or string using RegularExpressions.


Complete Html markup of webform:

<html xmlns="">
<head runat="server">
    <title>Remove special character’s from string</title>
    <form id="form1" runat="server">
                <td>Enter Username :</td>
                 <td><asp:TextBox ID="txtusername" runat="server" AutoPostBack="true"></asp:TextBox></td>
                <td>Enter Username :</td>
                <td><asp:TextBox ID="txtsuser" runat="server" Enabled="false"></asp:TextBox></td>

Add namespace

C# Code:
using System.Text.RegularExpressions;

VB.Net Code
Imports System.Text.RegularExpressionsCreate

Remove special characters
Create a method to remove special characters.  On textbox change event write the code.

C# Code:
public static string RemoveSpecialCharacterFromString(string str)
        return Regex.Replace(str, "[^a-zA-Z0-9]+", "");
  protected void txtusername_TextChanged(object sender, EventArgs e)
        string txt = txtusername.Text;
        string username = RemoveSpecialCharacterFromString(txtusername.Text.Trim());
        txtsuser.Text = username;

VB.Net Code
Public Shared Function RemoveSpecialCharacterFromString(str As String) As String
        Return Regex.Replace(str, "[^a-zA-Z0-9]+", "")
    End Function
Protected Sub txtusername_TextChanged(sender As Object, e As EventArgs) Handles txtusername.TextChanged
        Dim txt As String = txtusername.Text
        Dim username As String = RemoveSpecialCharacterFromString(txtusername.Text.Trim())
        txtsuser.Text = username
    End Sub

No comments:

Post a Comment