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?
Instead of ‘C’ put ‘{0:c}’
For more string formatting problems go here