简体   繁体   中英

How to format all textbox values on LostFocus event in Winform

I need to add commas to thousand position of every numerical value in any related text-box value upon lost-focus event. I have created the following function:

public static void FormatNumerical(this Control control)
{
    if (!(control is TextBox) || !control.Text.IsNumeric()) return;

    control.Text = String.Format("{0:n}", control.Text);
}

Is there a way to apply this method to all lost focus events for all my textboxes in my winform application in one shot?

Is that you need?

ProcessTextBoxes(this, true, (textbox) =>
{
  if ( !textbox.Focused && textbox.Text.IsNumeric() )
    textbox.Text = String.Format("{0:n}", textbox.Text);
});

private void ProcessTextBoxes(Control control, bool recurse, Action<TextBox> action)
{
  if ( !recurse )
    Controls.OfType<TextBox>().ToList().ForEach(c => action?.Invoke(c));
  else
    foreach ( Control item in control.Controls )
    {
      if ( item is TextBox )
        action.Invoke((TextBox)item);
      else
      if ( item.Controls.Count > 0 )
        ProcessTextBoxes(item, recurse);
    }
}

You can adapt this code and pass this for the form or any container like a panel and use recursivity or not to process all inners.

Also, you can do that on each Leave event and assign one to all needed:

private void TextBox_Leave(object sender, EventArgs e)
{
  var textbox = sender as TextBox;
  if ( textbox == null ) return;
  if ( textbox.Text.IsNumeric() )
    textbox.Text = String.Format("{0:n}", textbox.Text);
}

private void InitializeTextBoxes(Control control, bool recurse)
{
  if ( !recurse )
    Controls.OfType<TextBox>().ToList().ForEach(c => c.Leave += TextBox_Leave);
  else
    foreach ( Control item in control.Controls )
    {
      if ( item is TextBox )
        item.Leave += TextBox_Leave;
      else
      if ( item.Controls.Count > 0 )
        InitializeTextBoxes(item, recurse);
    }
}

public FormTest()
{
  InitializeComponent();
  InitializeTextBoxes(EditPanel, true);
}

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