Windows窗体中的十进制文本框 [英] Decimal Textbox in Windows Forms

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

问题描述

我正在做一个Financial Winforms应用程序,并且在控件上遇到了一些麻烦.

I am doing an Financial Winforms application and am having some trouble with the controls.

我的客户需要在所有位置(价格,折扣等)插入十进制值,我想避免重复进行某些验证.

My customer needs to insert decimal values all over the place (Prices, Discounts etc) and I'd like to avoid some of the repeating validation.

所以我立即尝试了适合我需要的MaskedTextBox(带有€00000.00"的蒙版),如果它不是针对焦点和蒙版的长度的话.

So I immediately tried the MaskedTextBox that would fit my needs (with a Mask like "€ 00000.00"), if it weren't for the focus and the length of the mask.

我无法预测我的客户要输入该应用程序的数量.

I can't predict how big the numbers are my customer is going to enter into the app.

我也不能指望他以00开始的所有内容都进入逗号.一切都应该对键盘友好.

I also can't expect him to start everything with 00 to get to the comma. Everything should be keyboard-friendly.

我是否缺少某些东西?或者除了标准的Windows窗体控件之外,没有其他方法(除了编写自定义控件之外)无法实现?

Am I missing something or is there simply no way (beyond writing a custom control) to achieve this with the standard Windows Forms controls?

推荐答案

这两个覆盖的方法对我有用(免责声明:此代码尚未投入生产.您可能需要修改)

This two overriden methods did it for me (disclaimer: this code is not in production yet. You may need to modify)

    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);
    }

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

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