限制c#中文本框十进制输入的最佳方法

Has*_*anG 3 c# vb.net winforms c#-3.0 c#-4.0

如何创建一个文本框,其中只能输入类似12.00或1231231.00或123123的数字

我已经做了很长的事情,我正在寻找最好,最快的方式.

小数分隔符也必须是特定于文化的:

Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 7

验证事件是为了做到这一点.删除表单上的ErrorProvider控件,以便巧妙地提醒用户她做错了什么.该事件还允许您以有意义的方式格式化文本框文本.像这样:

    private void textBox1_Validating(object sender, CancelEventArgs e) {
        // Empty strings okay?  Up to you.
        if (textBox1.Text.Length > 0) {
            decimal value;
            if (decimal.TryParse(textBox1.Text, out value)) {
                textBox1.Text = value.ToString("N2");
                errorProvider1.SetError(textBox1, "");
            }
            else {
                e.Cancel = true;
                textBox1.SelectAll();
                errorProvider1.SetError(textBox1, "Please enter a number");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)