Dot Net Learning Zone Blog

A blog about to learn Dot Net

How to validate text box with only numeric value with two decimal place

Posted by Rajesh on December 24, 2010

We have created a sample project in windows form in c#. There is a text box which accept only numeric value with decimal like 1234.56.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

string strNumber = “0123456789.”;

private void textBox1_Leave(object sender, EventArgs e)
{

textBox1.Text = Convert.ToDecimal ( textBox1.Text).ToString(“N2″).Replace (“,”,”");
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (strNumber.IndexOf(e.KeyChar) == -1)
{
e.Handled = true;
}

if ((textBox1.Text.IndexOf(‘.’) > -1) && (e.KeyChar == ‘.’))
{
e.Handled = true ;
}

}
}
}

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.