Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

c# - Winforms Format TextBox To Currency

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...