Problems with Backspace in Textbox

Asked

Viewed 447 times

0

I have a project to build a textbox that would only include hours and minutes (With Datetimerpicker, da para fazer tranquilo, however need to click in another field to change data, and I found this very bad for the client...

That way I programmed a Textbox to put a ":" to define it cute, without any problems.

However, when making you 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;
            }
        }
    }

It has something to do with using the Keypress event for Keydown on that occasion??

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

  • better use a maskedtextbox nay ?

  • Thank you very much!

1 answer

0


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

Just you change the if. I used the following condition:

If the character is a number, or a control (Backspace, delete, etc...) runs 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, only the if part. And if you’d like to check to see if you’ve only been pressured into Backspace, you could do so:

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

For more character codes, see the ASCII table:

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

  • Thank you very much!

  • @Cassiani, don’t forget to dial in the answer if you solved your problem. If you have any questions about the community visit the tour: https://answall.com/tour

Browser other questions tagged

You are not signed in. Login or sign up in order to post.