简体   繁体   中英

c# format textboxes to currency when they lose focus

I have several lists of text boxes on a form each representing a column of a database. I want to update the form each time the user exits one of the boxes for price. the name of this list is priceBox[]. I am aware of the lostFocus event but I cant seem to figure a way to get it to work for a collection and this list can grow so I cant have a fixed number. I dont have any code for this yet. if it helps the text box controls are contained in a panel named panel1.

I have tried searching and cant find anything on this. only for singular instances, like updating 1 text box.

sorry if this is a duplicate but I did try to search. also I am new to c#.

thanks.

One approach is adding a ControlAdded handler to the panel, so every time a new textbox is added, it automatically adds LostFocus handler for it. Step-by-step below:

For your panel you bind a handler ControlAdded event, which would be something like:

private void Panel1_ControlAdded(object sender, ControlEventArgs e)
{
    var tb = e.Control as TextBox;
    if (tb != null)
    {
        tb.LostFocus += new EventHandler(TextBox_LostFocus);
    }
}

Then in TextBox_LostFocus you can add whatever logic you want

void TextBox_LostFocus(object sender, EventArgs e)
{
    var tb = sender as TextBox;
    if (tb != null)
    {
        // modify tb.Text here, possibly like this...
        tb.Text = String.Format("{0:C}", Decimal.Parse(tb.Text));
    }
}

To update all existing controls (not tested)

foreach (TextBox in panel1.Controls)
{
    tb.LostFocus += new EventHandler(TextBox_LostFocus);
}

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