Accept only numbers by the TextBox in ASP.NET

If you want to do it in asp.net that your TextBox accept only number when user input in it. Use CompareField Validator for this type of problem, Normally we use CompareField Validator for password recheck. Today we use it for another purpose, now, take an example.

Accept Only integer type number by TextBox

Step-1 : Add webform into the project.
Step-2 : Take one TextBox and Button control onto the webform.
Step-3 : Also take one Required field and one compare field validator onto the web form.
Step-4 : Set Property of required field validator, these are

ControlToValidate="TextBox1"
Display="Dynamic"
ForeColor="#CC0000"
Text= "Required"

Step-5 : Set Property of CompareField Validator, these are

ControlToValidate="TextBox1"
 Display="Dynamic"
  ForeColor="#CC0000"
  Operator="DataTypeCheck"
   Type="Integer"
   Text= "Enter Only numbers"

Complete code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        Enter age :
        <asp:TextBox ID="TextBox1" runat="server" Width="172px"></asp:TextBox>
&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#CC0000">Required</asp:RequiredFieldValidator>

        <asp:CompareValidator ID="CompareValidator1" runat="server" 
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#CC0000" 
            Operator="DataTypeCheck" Type="Integer">Enter Only numbers</asp:CompareValidator>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" />
    
    </div>
    </form>
</body>
</html>

Code Generate the following Output

Accept only numbers by the TextBox in ASP.NET

Comments

Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites