Posts Tagged ‘KeyPress event’

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;
}

}