tags:

views:

1541

answers:

6

I am trying to ensure that the text in my control derived from TextBox is always formatted as currency.

I have overridden the Text property like this.

   public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {                
            double tempDollarAmount = 0;
            string tempVal = value.Replace("$", "").Replace(",","");
            if (double.TryParse(tempVal, out tempDollarAmount))
            {
                base.Text = string.Format("C", tempDollarAmount);
            }
            else
            {                 
                base.Text = "$0.00";
            }                
        }
    }

Results:

  • If I pass the value "Text" (AmountControl.Text = "Text";) , the text of the control on my test page is set to "$0.00", as expected.
  • If I pass the value 7 (AmountControl.Text = "7";) , I expect to see "$7.00", but the text of the control on my test page is set to "C".

I assume that I am missing something very simple here. Is it something about the property? Or am I using the string format method incorrectly?

+9  A: 

Instead of "C" put "{0:c}"

For more string formatting problems go here

Jason Punyon
Thanks. I marked this as the answer, since you're first. Thanks for the link.
NetHawk
+1  A: 

Needs to be "{0:C}"

matt_dev
+2  A: 

You can also use tempDollarAmount.ToString("C").

Joe
Thanks, Joe. I'm glad to see how the "C" format string is actually used.
NetHawk
+1  A: 

it should be "{0:C}"

jmein
+1  A: 

Yes, it should be:

base.Text = string.Format("{0:C}", tempDollarAmount);
Gonzalo Quero
+1  A: 

It should be:

base.Text = string.Format("{0:C}", tempDollarAmount);

And please don't use double to represent currency, use decimal instead.

Stu Mackellar