简体   繁体   中英

Textbox Number Formating & start with zero & accept only Numbers

I am using below Property example to make some calculation on textbox and if textbox is null I am assigning zero to it so calculation won't fail as you can see I am using Math.Round and I want to make several checks on these textbox input like

  1. textbox that only accepts numbers I searched and found method 1

  2. I want my textbox to be formated I searched and found Method 2

Now my question is ..

Is there any way to mareg all these method in the property method I am using so my code won't be like "spaghetti code" ?

is there any better ways to do these checks ?

Thank you in advance

Property example

    public double ItemPriceResult
    {
        get
        {
            return Math.Round(ItemCost * RevenuePercentage / 100 + ItemCost, 0);
        }
    }

Method 1

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
    {
        MessageBox.Show("Please enter only numbers.");
        textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    }
}

Method 2

textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));

UPDATE after some answers

MaskedTextBox seems fit my needs I read and searched and below some question if you kindly would like to help me

I need to use MaskedTextBox because I can set it to accept number and I can also force number formating so

also I need to make number textboxs easer to read for users

so 1000 will be come 1,000 and 10000 will be come 10,000

then according to Microsoft Docs formating MaskedTextBox to fit my needs Masked MaskedTextBox with 999,999,999 ,
但是我的问题是格式不正确,如下图所示

second I do not want the PromptChar to be visible I google it but none of search result did it

Try this , it will accept only numbers and u can format the string as u want using regex.

 public static string ToMaskedString(this String value)
  {
    var pattern = "^(/d{2})(/d{3})(/d*)$";
    var regExp = new Regex(pattern);
    return regExp.Replace(value, "$1-$2-$3");
  }

You have a TextBox . Alas you don't tell what kind of TextBox you use. System.Windows.Forms.TextBox? System.Web.UI.MobileControls.TextBox?

You write " if text box is null I am assigning zero to it ". I assume that you mean that if no text is entered in the text box you assume that 0 is entered.

Furthermore you want to format the output of the text box whenever the text is changed. So while the operator is typing text you want to change this text? For the operator this is very annoying.

Wouldn't you prefer that the operator is obliged to type his text in the format you desire, helping him visually. For this you may use the class MaskedTextBox

The MaskedTextBox has a property Mask, which forces the operator to type in a certain format. I'm not really familiar with what you do with the format {0:#,##0.00} , but I assume you want the output double in a real format with two digits after the decimal point using the decimal point and the thousand separator as common in the current culture.

via the designer put in initialize component:

this.maskedTextBox1.Mask = "99990.00";

after adding the event for text changed:

private void maskedtextBox1_TextChanged(object sender, EventArgs e)
{
   double enteredValue = 0.0; // value to use when empty text box
   if (!String.IsNullOrEmpty(this.maskedtextBox1.Text))
   {
      enteredValue = double.Parse(maskedTextBox1.Text, myFormatProvider)
   }
   ProcessEnteredValue(enteredValue);
}

}

After your edit, the specifications have changed.

  • While entering the number in the text box, the operator should not have any visual feedback of the formatting of his number.
  • The operator is free to enter the real number in any commonly used format.
  • The value of the text box should not be used while the operator is editing the text box.
  • Only after editing is finished, the value of the text box should be interpreted for correctness, and if correct it should be used.
  • The actually used value should be displayed in the text box in a defined format.

The desire not to show any visual feedback while entering is understandable. After all, the program doesn't care whether the operator types 1000 , 1000.00 , or even 1.0E3 .

The MaskedTextBox is especially used to force the operator to enter his number in a given format. Since this is not desired, my advise would be to use a TextBox instead of a MaskedTextBox .

However, because you give the operator the freedom to enter his number in any way he wants, including copy-paste, repairing typing errors, etc. you'll have to add the possibility for the user to express to the program that he has finished entering the number.

An often used method in the windows UI would be a Button . Another possibility would be the enter button . Be aware though that this is not really standard within windows. It might make learning your program a little bit more difficult.

So after the operator notified that he finished editing and the corresponding event function is called, your code could be:

// Get the numberformat to use, use current culture, or your own format
private readonly IFormatProvider myNumberFormat = CultureInfo.CurrentCulture.NumberFormat

private void OperatorFinishedEditing(TextBox box)
{
    // read the text and try to parse it to a double
    // accepting all common formats of real numbers in the current culture
    bool valueOk = true;
    double resultValue = 0;
    if (!String.IsNullOrEmpty(box.Text))
    {
       bool valueOk = Double.TryParse(box.Text, out resultValue);
    }

    if (valueOk)
    {
        box.Text = FormatResultValue(resultValue);
        ProcessValue(resultValue);
    }
    else
    {
        ShowInputProblem();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM