F
F
Frip2019-04-11 00:35:50
C++ / C#
Frip, 2019-04-11 00:35:50

Input handler in TextBox via KeyPress event?

There is a certain TextBox. It must contain numbers (integer or floating point) separated by spaces.
Like this format:


10 11.2 6 3 5 6.11

Also, I tried to use the code below, which allows you to enter only numbers in the TextBox, and in which case it replaces the separator with the desired one.
spoiler
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Правильными символами считаются цифры,
            // запятая, <Enter> и <Backspace>.
            // Будем считать правильным символом
            // также точку, на заменим ее запятой.
            // Остальные символы запрещены.
            // Чтобы запрещенный символ не отображался 
            // в поле редактирования,присвоим 
            // значение true свойству Handled параметра e
 
            if ((e.KeyChar >= '0') && (e.KeyChar <= '9'))
            {
                // цифра
                return;
            }
 
            if (e.KeyChar == '.')
            {
                // точку заменим запятой
                e.KeyChar = ',';
            }
 
            if (e.KeyChar == ',')
            {
                TextBox textBox = sender as TextBox;
                if (textBox.Text.IndexOf(',') != -1)
                {
                    // запятая уже есть в поле редактирования
                    e.Handled = true;
                }
                return;
            }
 
            if (  Char.IsControl (e.KeyChar) )
            {
                // <Enter>, <Backspace>, <Esc>
                if ( e.KeyChar == (char) Keys.Enter)
                    // нажата клавиша <Enter>
                    // установить курсор на кнопку OK
                    button1.Focus(); 
                return;
            }
 
            // остальные символы запрещены
            e.Handled = true;
        }


but I'm completely unable to set logic for it, so that only numbers can be entered between spaces, so that there is only 1 separator.
Is it possible to do this through an event handler so as not to cause an error / re-entry for the user.
I will be very grateful for any hints.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BasiC2k, 2019-04-11
@BasiC2k

In the KeyPress event parse the contents of the textBox
Get a string array from it by splitting the contents via Split. The separator is a space.
Further - you check each element of an array on IsNumeric.
If at least one element of the array does not match the condition, then display an errorProvider next to the text field with an error message.
Don't forget to handle Ctrl+V

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question