我正在进行Financial Winforms应用程序,并且在控件上遇到了一些问题。

我的客户需要在整个地方插入小数值(价格,折扣等),我想避免一些重复验证。

所以我立刻尝试了适合我需要的MaskedTextBox(如“€ 00000.00”这样的掩码),如果它不是焦点和面具的长度。

我无法预测我的客户将进入应用程序的数量有多大。

我也不能指望他用00开始一切来到逗号。一切都应该是键盘友好的。

我是否遗漏了某些东西,或者除了编写自定义控件之外没有办法用标准的Windows窗体控件来实现这一点?

有帮助吗?

解决方案

这两个被覆盖的方法为我做了(免责声明:此代码尚未生产。您可能需要修改)

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back 
            & e.KeyChar != '.')
        {
            e.Handled = true;
        }

        base.OnKeyPress(e);
    }

    private string currentText;

    protected override void OnTextChanged(EventArgs e)
    {
        if (this.Text.Length > 0)
        {
            float result;
            bool isNumeric = float.TryParse(this.Text, out result);

            if (isNumeric)
            {
                currentText = this.Text;
            }
            else
            {
                this.Text = currentText;
                this.Select(this.Text.Length, 0);
            }
        }
        base.OnTextChanged(e);
    }

其他提示

您需要一个自定义控件。只需在控件上捕获Validating事件,并检查字符串输入是否可以解析为小数。

我认为您不需要自定义控件,只需为验证事件编写一个十进制验证方法,并将其用于您需要验证的所有位置。不要忘记包含 NumberFormatInfo ,它将处理逗号和数字符号。

您只需要通过数字和小数符号,并避免使用双十进制符号。另外,这会在起始十进制数之前自动添加0。

public class DecimalBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (e.KeyChar == ',')
        {
            e.KeyChar = '.';
        }

        if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        if(e.KeyChar == '.' )
        {
            if (this.Text.Length == 0)
            {
                this.Text = "0.";
                this.SelectionStart = 2;
                e.Handled = true;
            }
            else if (this.Text.Contains("."))
            {
                e.Handled = true;
            }
        }

        base.OnKeyPress(e);
    }
}

另一种方法是阻止你不想要的东西,并在完成它时进行格式化。

class DecimalTextBox : TextBox
{
    // Handle multiple decimals
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (e.KeyChar == '.')
            if (this.Text.Contains('.'))
                e.Handled = true;

        base.OnKeyPress(e);
    }

    // Block non digits
    // I scrub characters here instead of handling in OnKeyPress so I can support keyboard events (ctrl + c/v/a)
    protected override void OnTextChanged(EventArgs e)
    {
        this.Text = System.Text.RegularExpressions.Regex.Replace(this.Text, "[^.0-9]", "");
        base.OnTextChanged(e);
    }

    // Apply our format when we're done
    protected override void OnLostFocus(EventArgs e)
    {
        if (!String.IsNullOrEmpty(this.Text))
            this.Text = string.Format("{0:N}", Convert.ToDouble(this.Text));

        base.OnLostFocus(e);
    }


}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top