简体   繁体   English

如何在 Winform 中格式化 LostFocus 事件的所有文本框值

[英]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.在失去焦点事件时,我需要在任何相关文本框值中的每个数值的千 position 中添加逗号。 I have created the following function:我创建了以下 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?有没有办法一次性将此方法应用于我的winform应用程序中所有文本框的所有丢失焦点事件?

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.您可以调整this代码并将其传递给表单或任何容器(如面板),并使用递归或不处理所有内部。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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