Problems with BackSpace in TextBox

0

I have a project to set up a textbox that would only include hours and minutes (With DateTimerPicker, you have to do it quietly, however, you need to click on another field to change data, and I found this very bad for the client ... < p>

In this way, I programmed a TextBox so that I would put a ":" to define it cute, without any problems.

But , when doing so accept only numbers it blocks me from using backspace (ASCII-8) ...

private void txtHoraMarcada_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!(char.IsDigit(e.KeyChar)))
        {
            e.Handled = true;
        }
        else
        {
            TextBox mascara = sender as TextBox;
            if (mascara.Text.Length == 2)
            {
                mascara.Text += ":";
                txtHoraMarcada.SelectionStart = 3;
            }
        }
    }

Is there anything to do with using the Keypress event for KeyDown on that occasion ??

I just needed to release to erase instead of having to select everything to give Del and write again, Thanks!

    
asked by anonymous 29.01.2018 / 22:39

1 answer

0

I think I could use a MaskedTextBox that would suit you better in this situation. But answering the question:

Just change the if . I used the following condition:

  

If the character is a number, or a control (backspace, delete, etc ...) I execute its logic, otherwise the event is manipulated (does nothing).

private void txtHoraMarcada_KeyPress(object sender, KeyPressEventArgs e)
{
    if (char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar))
    {
        TextBox mascara = sender as TextBox;
        if (mascara.Text.Length == 2)
        {
            mascara.Text += ":";
            txtHoraMarcada.SelectionStart = 3;
        }
    }
    else
    {
        e.Handled = true;
    }
}
  

Ps: I did not analyze your logic to apply the mask, just the part of if. And, if you want to check if you just pressed backspace, you could do this:

if (e.KeyChar == (char)8)
{
   //foi pressionado backspace
}

For more character codes, see the ASCII table:

link

    
29.01.2018 / 23:01