-1

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,
but my problem is formating not correct as you can see at image below

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

sam
  • 2,493
  • 6
  • 38
  • 73
  • Which technology do you use? WPF? – JuP Mar 01 '17 at 08:41
  • Are you using Windows Forms or WPF? Have you looked into a MaskedTextBox? – Jono Stewart Mar 01 '17 at 08:41
  • @JonoStewart I am using windows forms and I have no idea about MaskedTextBox – sam Mar 01 '17 at 08:56
  • 1
    In WinForm, you can use NumericUpDown control. – GSP Mar 01 '17 at 09:05
  • @sam, a quick google of MaskedTextBox will link you to a very comprehensive page with examples at the (very) bottom – Jono Stewart Mar 01 '17 at 10:31
  • @GSP this option is not good for me since I need something fit currency maskedtextbox seems what I really want but I am new to it ... thanks my friend – sam Mar 01 '17 at 20:57
  • @JonoStewart thank you my friend I searched and found that this option is what I need i have sevral question and problem and I am ganna post new question look for answer – sam Mar 01 '17 at 20:59
  • @sam have a look at this SO answer http://stackoverflow.com/questions/1459797/hiding-the-promptchar-for-nets-maskedtextbox - it mentions setting the PromptChar to a space, and the HidePrompt value – Jono Stewart Mar 02 '17 at 13:41

3 Answers3

1

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");
  }
Ashu
  • 467
  • 1
  • 7
  • 19
1

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

}

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • yes I am using windows form and yes I meant if no text is entered in the `textbox` I assume that 0 is entered. I just want to make number easer to read for user by setting ( , ) thousand separator and I do not really care about decimal separator and as you said `MaskedTextBox` seems what I need please I had update my post with some question on `maskedtextbox` after searching about suggestion so kindly if you would like to help me in understanding it – sam Mar 01 '17 at 21:09
0

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 aMaskedTextBox.

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();
    }
}
Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • uh so I am going to use textbox I was planing and all you have said is 100% is what I want ... the only one thing i want to do is just to allow user to enter only number within that textbox nothing [0-9] that's all I want then after user finishing his data enter i want to format these number to make them easier to read in some cases I the textbox is read only and their value came out from multiplying another two textbox or directly from oracle database in that case I just need to format these number – sam Mar 03 '17 at 14:42