Hi RachelBillings-9127,
Do you want to enter only numbers in the textbox?
If so, you can determine the value of keychar in the textBox_KeyPress event.
The keychar corresponding to the numbers 0-9 is 48-57, the decimal point is 46, and the backspace is 8.
Here is a code example you can refer to.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Determine whether the key is the type to be input.
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
e.Handled = true;
//Handling of decimal points.
if ((int)e.KeyChar == 46) //Decimal point
{
if (textBox1.Text.Length <= 0)
e.Handled = true; //The decimal point cannot be in the first place
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(textBox1.Text, out oldf);
b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
Best Regards,
Daniel Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.