简体   繁体   中英

Formatting data in a textbox in C#

I've got a dropdown control on a form. The results of this dropdown need to be written to a hidden textbox, but when they're written to the textbox it needs to be in the format "XX.XX". So, if the user selects "1.0", it needs to be written to the textbox as "01.00".

I'm a native Access/VBA programmer, and it's fairly easy to do in VBA. How would I do this in C# code-behind?

What I have now is:

    protected void ddlCIT_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtCIT.Text = ddlCIT.SelectedValue;
    }

This was before I knew about this requirement., so it doesn't address the formatting issue at all. I'm sure it's got to be something like:

txtCIT.Text = Format(ddlCIT.SelectedValue, "##.##");

or something, but I just can't figure it out. None of the examples I've found were doing anything close to what I need.

EDIT

As per asven's answer, I've now got the following code:

 string ddlCITVal = ddlCIT.SelectedValue.ToString();
 txtCIT.Text = string.Format("{0:#0.0#}", ddlCITVal);
 string blearg = string.Format("{0:0.0#}", ddlCITVal);

Both my textbox and my string "blearg" show a result of "2.0" in the Immediate window when I select "2.0" from the dropdown. I also tried using "{0:00.00}" in the format clause with identical results.

I'm using VS2012 if that matters.

尝试

string.Format("{0:00.00}", ddlCIT.SelectedValue);

You could go one step further and use a custom textbox. This allows you to have validation and formatting built in:

public class NumDoubTextbox : TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            double temp = 0;
            if (double.TryParse(value, out temp))
                //Formatting as a float then padding left with 0's should give the format you want
                base.Text = temp.ToString("F2").PadLeft(5,'0');
            else
                //Handle invalid input here. 
                base.Text = "--.--";
        }
    }
}

You can put this in a separate project and compile it and have it included in the toolbox so that it can be used at design time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM