5

I am new to Winforms development and I going to be displaying data to my users in a textbox. The textbox will be databound with data that is currency so I am trying to Format the value that is being displayed.

I looked at a Masked Text Box but that isn't exactly what I am looking for because it doesn't put the cents after the decimal.

Do I need to code for each textbox similar to this?

TextBox.Text = DataSet.DataView[0].Amount.ToString("c");

I have alot of textboxes that need to be formatted so I am wondering if I need to do this for each one. Does anyone have any suggestions?

wickedone
  • 542
  • 1
  • 6
  • 18

2 Answers2

5

You can create your own TextBox derived from standard one

 public class TextBoxEx : TextBox
{
    public string Format { get; set; }

    private object datasource = new object();
    public object Datasource
    {
        get { return datasource; }
        set 
        {
            datasource = value;
            if (datasource == null)
                base.Text = string.Empty;
            else if(string.IsNullOrWhiteSpace(Format))
                base.Text = datasource.ToString();
            else
                base.Text = string.Format("{0:"+ Format + "}",datasource);
        }
    }
}

Usage:

   textbox.Format = "c";
   textbox.Datasource = DataSet.DataView[0].Amount;
Stecya
  • 22,896
  • 10
  • 72
  • 102
  • so I still will have to code for each one, instead of just dropping a textbox on the form in design mode? – wickedone Aug 31 '11 at 14:53
  • Nope. This TextBoxEx will appear in toolbox after your build it. And then you can set Format in properties window – Stecya Aug 31 '11 at 15:01
  • I get the red squiggly line under base.Text = datasource.ToString(Format); with a error that the ToString has no parameters but is declared with one argument – wickedone Aug 31 '11 at 15:08
  • thanks for the help. I would give you +1 but I don't have enough rep yet. :( – wickedone Aug 31 '11 at 15:47
  • 7
    I also just found that I can do this on the property window for the textbox, under DataBindings, Advanced and choose Currency – wickedone Aug 31 '11 at 16:13
1

Imagine you have the total coming from a double variable such as mySumInvestment and you want to place it a textbox with US Currency Format. Then this is something you could do

textBox5.Text = mySumInvestment.ToString("c", CultureInfo.CreateSpecificCulture("en-US")); // In order to format as currency
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73