Answer the question
In order to leave comments, you need to log in
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
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;
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question