Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a textbox that gets a decimal value say 10500.00 the problem is that the way I have it, when you enter a value and then enter the decimals it would not allow you to backspace or clear the textbox to input a new value.. it just gets stuck.. I have tried to set the value back to 0.00 but i think i placed it on the wrong place because it wont change it. Here is my code

 private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @".dd");
            if (matchString)
            {
                e.Handled = true;
            }

            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }

            // only allow one decimal point
            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }

What type of change do you suggest so that I may be able to backspace or clear the texbox an enter a new value?.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
139 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can trap for the Backspace (BS) char (8) and, if found, set your handle to false.

Your code may look like this...

....
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
    e.Handled = true;
}

if (e.KeyChar == (char)8)
    e.Handled = false;

A suggestion to make your code a bit more intuitive to interpret what your event handler is doing, you may want to create a var that implies the logic you are implementing. Something like...

private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e)
{
    bool ignoreKeyPress = false; 

    bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @".dd");

    if (e.KeyChar == '') // Always allow a Backspace
        ignoreKeyPress = false;
    else if (matchString)
        ignoreKeyPress = true;
    else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
        ignoreKeyPress = true;
    else if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
        ignoreKeyPress = true;            

    e.Handled = ignoreKeyPress;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...