G
G
goldolov_na2019-05-29 10:32:45
C++ / C#
goldolov_na, 2019-05-29 10:32:45

How in this textbox'a code to make it possible to press the backspace key (erase)?

you need to modify the code so that the backspace key is active (it works in the textbox)

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            
            string Symbol = e.KeyChar.ToString();

            if (!Regex.Match(Symbol, @"[а-яА-Я]").Success )
            {
                e.Handled = true;
            }

        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2019-05-29
@goldolov_na

Use KeyDown instead of KeyPress. KeyDown receives not a printable character, but a key code, including control keys.
In your case, both events need to be called. KeyDown is called first, and if it hasn't done any processing work (e.Handled = true is not specified), then the KeyPress handler will be called.
Here is an example code for handling backspace:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Back)
    {
        var selectionStart = textBox1.SelectionStart;
        if (textBox1.SelectionLength > 0)
        {
            textBox1.Text = textBox1.Text.Substring(0, selectionStart) + textBox1.Text.Substring(selectionStart + textBox1.SelectionLength);
            textBox1.SelectionStart = selectionStart;
        }
        else if (selectionStart > 0)
        {
            textBox1.Text = textBox1.Text.Substring(0, selectionStart - 1) + textBox1.Text.Substring(selectionStart);
            textBox1.SelectionStart = selectionStart - 1;
        }
        
        e.Handled = true;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question