Menu ▼

Previous Next

Custom textbox to allow only numbers :

For creating custom controls that allow only numbers follow the steps.

  • Add a new Class Library project to your soluiton
  • Add class to the project and name it as NumbersTextBox
  • Add System.Web reference to the Project
  • Inheit the class from TextBox
  • Now override the Render event
  • Build the project
  • Re-Build the solution, now check the toolbox. You should be able to see the custom contol in your soluion toolbox.

Source Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Web.UI.WebControls;

using System.ComponentModel;

 

namespace CustomControls

{

    public class NumbersTextBox : TextBox

    {

 

        protected override void Render(System.Web.UI.HtmlTextWriter writer)

        {

            this.Attributes["onkeypress"] = "return onlyNos(event,this);" + this.Attributes["onkeypress"];

            base.Render(writer);

            writer.Write(@"<script language='javascript'>

                            function onlyNos(e, t) {

                                try {

                                    if (window.event) {

                                        var charCode = window.event.keyCode;

                                    }

                                    else if (e) {

                                        var charCode = e.which;

                                    }

                                    else { return true; }

                                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {

                                        return false;

                                    }

                                    return true;

                                }

                                catch (err) {

                                    alert(err.Description);

                                }

                            }

                            </script>");

 

        }

 

    }

 

}

 

 

Previous Next




Search dotnetlearners.com