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 solution
  • Add class to the project and name it as NumbersTextBox
  • Add System.Web reference to the Project
  • Inherit 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 control in your solution 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(@""); } } }