h1

Numeric only text box in .net Winforms

July 18, 2011

We can create Numeric only text boxes in .Net Windows forms application with adding below code in Key Press Event.

Numeric only text boxes

private void txtBox_KeyPress(object sender, KeyPressEventArgs e)

{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != ‘.’)
{
e.Handled = true;
}

// only allow one decimal point
if (e.KeyChar == ‘.’ && (sender as TextBox).Text.IndexOf(‘.’) > -1)
{
e.Handled = true;
}
}

 

Integer only text boxes

private void txtBox_KeyPress(object sender, KeyPressEventArgs e)

{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) )
{
e.Handled = true;
}

}

Advertisements

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: