Thursday, 29 December 2011

Restrict TextBox from accepting numeric digits..

Hi friends, I’m adding here a tutorial code snippet based on Validating Textbox for accepting numeric keys only..
Step1. Write a class for user defined textbox as shown below or drag from VSIDE and add event handler to textbox

class NumbersOnly:TextBox
{
public NumbersOnly()
{
this.KeyPress += new KeyPressEventHandler(text_numberhandle);
}
private void text_numberhandle(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{ e.Handled = true; }
}
}



Second Method..
You can add textbox handler to Designer.cs file and call it from Form source file as mentioned below


// textBox1
//

this.textBox1.Location = new System.Drawing.Point(92, 62);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 0;
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(
text_numberhandle);

and then call it from your Form1 code.


//Form1.cs
private void text_numberhandle(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}

No comments:

Post a Comment