In this article I am going to explain how to remove special
character’s from string or text typed/entered in Textbox in asp.net.
Description:
I want to remove special characters from text typed/entered in Textbox or string using RegularExpressions.
Implementation:
Complete
Html markup of webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Remove special
character’s from string</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Enter Username :</td>
<td><asp:TextBox ID="txtusername" runat="server" AutoPostBack="true"></asp:TextBox></td>
</tr>
<tr>
<td>Enter Username :</td>
<td><asp:TextBox ID="txtsuser" runat="server" Enabled="false"></asp:TextBox></td>
</tr>
</table>
</div>
</form>
</body>
</html>
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