You need to use the KeyPress
event and add the below logic to determine what is being pressed and where the entered value is going to be placed.
When you set the e.Handled
value to true then you are telling the system to ignore the users input.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// Only allow digits, decimal points and control characters (Backspace, delete, etc)
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
(e.KeyChar != '.'))
{
e.Handled = true;
}
int PointIndex = (sender as TextBox).Text.IndexOf('.');
// only allow one decimal point and one digit before decimal point
if (((e.KeyChar == '.') && PointIndex > -1) ||
(e.KeyChar == '.' && textBox1.SelectionStart > 1) ||
(PointIndex == 1 && textBox1.SelectionStart <= PointIndex))
{
e.Handled = true;
}
}
This code validates the users input as they are typing.
EDIT:
Also since this code only validates the input as the user is typing you will also want to prevent them pasting in invalid values. You can do this by setting the ShortcutsEnabled
property of the textbox to false.