具有十进制输入改进的文本框 [英] Textbox with decimal input improvement

查看:45
本文介绍了具有十进制输入改进的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个获取十进制值的文本框说 10500.00 问题是我的方式,当你输入一个值然后输入小数时,它不允许你退格或清除输入新值的文本框..它只是卡住了..我试图将值设置回 0.00 但我想我把它放在错误的地方,因为它不会改变它.这是我的代码

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(), @"\.\d\d");
            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?.

推荐答案

您可以为 Backspace (BS) 字符 (8) 设置陷阱,如果找到,请将句柄设置为 false.

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;

建议让您的代码更直观地解释您的事件处理程序正在做什么,您可能需要创建一个 var 来暗示您正在实现的逻辑.像……

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(), @"\.\d\d");

    if (e.KeyChar == '\b') // 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;
}

这篇关于具有十进制输入改进的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆