How to make a textbox accept only digits and formats numbers with commas?

帅比萌擦擦* 提交于 2019-12-29 07:02:50

问题


I need a text box that:

(1) only accepts digits as characters.

(2) automatically continues to format numeric values with commas as the user types into it.

For example,

     1 becomes        1.00
    10 becomes       10.00
   100 becomes      100.00
  1000 becomes    1,000.00
 10000 becomes   10,000.00
100000 becomes 1,00,000.00

How to achieve that?


回答1:


Formatting a number while the user is typing in general works very poorly. You should use a MaskedTextBox for that. Plenty of code about on the Internet that shows how to filter KeyPress so only digits can be entered. Most of it is trivially defeated by using the Paste command.

The sane way is to treat the user capable of basic skills like typing a number and gently remind her that she got it wrong. The Validating event is made for that. Which is also the perfect time to format the number. Add a new class to your project and paste this code:

using System;
using System.ComponentModel;
using System.Windows.Forms;

public class NumberBox : TextBox {
    public NumberBox() {
        Fraction = 2;
    }

    public ErrorProvider ErrorProvider { get; set; }

    [DefaultValue(2)]
    public int Fraction { get; set; }

    public event EventHandler ValueChanged;
    public decimal Value {
        get { return this.value; }
        set {
            if (value != this.value) {
                this.value = value;
                this.Text = Value.ToString(string.Format("N{0}", Fraction));
                var handler = ValueChanged;
                if (handler != null) ValueChanged(this, EventArgs.Empty);
            }
        }
    }

    protected override void OnValidating(CancelEventArgs e) {
        if (this.Text.Length > 0 && !e.Cancel) {
            decimal entry;
            if (decimal.TryParse(this.Text, out entry)) {
                if (ErrorProvider != null) ErrorProvider.SetError(this, "");
                Value = entry;
            }
            else {
                if (ErrorProvider != null) ErrorProvider.SetError(this, "Please enter a valid number");
                this.SelectAll();
                e.Cancel = true;
            }
        }
        base.OnValidating(e);
    }

    protected override void OnEnter(EventArgs e) {
        this.SelectAll();
        base.OnEnter(e);
    }


    private decimal value;
}

Compile. Drop the new NumberBox control from the top of the toolbox onto your form. Also drop an ErrorProvider on the form so typing mistakes can be reported in modest way, set the ErrorProvider property of the new control. Optionally modify the Fraction property. You can subscribe the ValueChanged event to know when the value was modified.




回答2:


Have you tried looking at a masked text box?

http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.80).aspx




回答3:


There is a very simple way: using TextChanged and Leave events.

private void textBox_TextChanged(object sender, EventArgs e)
{
   decimal theNumber;
   if(!decimal.TryParse((sender as TextBox).Text, out theNumber))
   {
      (sender as TextBox).Text = string.empty;
   }
}

Do not try to format the number in TextChanged event it gets messy. Then when the user leaves the text box change the format.

private void textBox_Leave(object sender, EventArgs e)
{
   // Since you were validating the number while typing now there is no need for TryParse
   decimal theNumber = decimal.Parse((sender as TextBox).Text);
   (sender as TextBox).Text = string.Format("{0:N2}", theNumber);
}

Note: This is plain and simple, if you need something more elaborated (best practices and all that stuff...) refer to Hans answer.




回答4:


I dont know if this is gonna help, but here it goes:

try
{
    double number = Convert.toDouble(textBox.Text);
    string[] digits = Regex.Split(textBox.Text, @"\W+");
    int x = 0;
    List<string> finalNumber = new List<string>();
    while(x < numbers.Length)
    {
        if(digits[x] == ".")
            break;
        if(x%3 = 0 && x != 0)
        {
            finalNumber.Add(",");   
        }
        finalNumber.Add(digits[x]);
        x++;
    }
    string finalNumberJoined = "";
    foreach(var digit in finalNumber)
    {
        finalNumberJoined = finalNumberJoined + digit;
    }
}
catch
{
    //not a number
}


来源:https://stackoverflow.com/questions/15163564/how-to-make-a-textbox-accept-only-digits-and-formats-numbers-with-commas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!