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

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

本文介绍了如何在Winform中的LostFocus事件上格式化所有文本框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在失去焦点事件后将逗号添加到任何相关文本框值中每个数字值的千位.我创建了以下功能:

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

有没有办法一次将这种方法应用于winform应用程序中所有文本框的所有丢失焦点事件?

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

推荐答案

您需要吗?

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

您可以修改此代码,并将 this 传递给表单或面板之类的任何容器,并使用递归性或不处理所有内部内容.

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.

此外,您可以在每个请假事件上执行此操作,并将其分配给所有需要的事件:

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

这篇关于如何在Winform中的LostFocus事件上格式化所有文本框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:24