Problems with backspace in TextBox

I have a project to set up a textbox that would only include hours and minutes (with DateTimerPicker, to do quiet, however need to click on another field to change data, and I found it very bad for the client...

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

But , making it accept only numbers 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;
            }
        }
    }

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

Just needed to release to delete instead of having to select all to give Del and write again, thank you!

 0
Author: Cassiani, 2018-01-29

1 answers

I think I could use a MaskedTextBox that would serve you better in that 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 run your 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 didn't parse your logic to apply the mask, only the if part. And, if you want to check if only the backspace, could do like this:

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

For more character codes, see the ASCII table:

Https://pt.wikipedia.org/wiki/ASCII

 0
Author: Rovann Linhalis, 2018-01-29 22:01:48