How to format all textbox values on LostFocus event in Winform

旧城冷巷雨未停 提交于 2021-02-05 08:42:18

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/62761889/how-to-format-all-textbox-values-on-lostfocus-event-in-winform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!