I would like to allow only certain keys to be valid for my TextBox control. I have set it up as follows and it works fine.

private void TextBox_MapInputMin_KeyDown(object sender, KeyEventArgs e)
        {
            if (!IsFloatingPointTextBoxValid(e, textBox_MapInputMin))
            {
                // 'Handled' property stops key from being entered into the control
                e.Handled = true;
                return;
            }
        }

        private bool IsFloatingPointTextBoxValid(KeyEventArgs e, TextBox textBox)
        {
            if (e.Shift)
            {
                return false;
            }
            else if (e.Key == Microsoft.Xna.Framework.Input.Keys.Back)
            {
                return true;
            }
            else if (e.Key == Microsoft.Xna.Framework.Input.Keys.Left || e.Key == Microsoft.Xna.Framework.Input.Keys.Right)
            {
                return true;
            }
            else if (textBox.Text.Length < 7)
            {
                // Only allow character input if there are less than 7 characters

                if (e.Key == Microsoft.Xna.Framework.Input.Keys.OemPeriod || e.Key == Microsoft.Xna.Framework.Input.Keys.Decimal)
                {
                    return textBox.Text.Contains(".") ? false : true;
                }
                else if ((e.Key >= Microsoft.Xna.Framework.Input.Keys.D0) && (e.Key <= Microsoft.Xna.Framework.Input.Keys.D9))
                {
                    return true;
                }
                else if ((e.Key >= Microsoft.Xna.Framework.Input.Keys.NumPad0) && (e.Key <= Microsoft.Xna.Framework.Input.Keys.NumPad9))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

It works fine until I hold a key down that is. Repeating keys aren't picked up by the event and can be entered without being checked.

How do I prevent repeating keys from being entered incorrectly and make them undergo the same processing?

The following code works fine for allowing only numeric data and adding only one decimal point it also works fine for key hold

void textBox1_KeyPress(object sender, System.Windows.Forms.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;
            }
           
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.