【问题标题】:Simplifying TextChange Event Handler for Multiple TextBox controls为多个 TextBox 控件简化 TextChange 事件处理程序
【发布时间】:2015-06-02 21:53:01
【问题描述】:

我只是想知道是否可以简化这些代码?我有多个文本框具有相同的 textchange 事件

    private void txtOvertimeHours_TextChanged(object sender, EventArgs e)
    {
        if (txtOvertimeHours.Text.Length <= 0 || 
            txtOvertimeHours.Text == null || 
            txtOvertimeHours.Text == "0.00" || 
            txtOvertimeHours.Text == "0" || 
            txtOvertimeHours.Text == "0.0")
        {
            txtOvertimeHours.Text = "0.00";
        }

    }

    private void txtAllowance_TextChanged(object sender, EventArgs e)
    {
        if (txtAllowance.Text.Length <= 0 ||
            txtAllowance.Text == null ||
            txtAllowance.Text == "0.00" ||
            txtAllowance.Text == "0" ||
            txtAllowance.Text == "0.0")
        {
            txtAllowance.Text = "0.00";
        }
    }

//等等

【问题讨论】:

  • Winforms、webforms、wpf、什么?
  • winform 先生@JohnSaunders

标签: c# winforms visual-studio-2010 visual-studio


【解决方案1】:

另一种方式。您可以对多个事件使用相同的事件处理程序:

private void ZeroOutTextBox_TextChanged(object sender, EventArgs e)
{
    TextBox txt = (TextBox) sender;

    if (txt.Text.Length <= 0 ||
        txt.Text == null ||
        txt.Text == "0.00" ||
        txt.Text == "0" ||
        txt.Text == "0.0")
    {
        txt.Text = "0.00";
    }
}

您可能还可以简化条件。下面的代码我没有测试过:

private void ZeroOutTextBox_TextChanged(object sender, EventArgs e)
{
    decimal result;
    TextBox txt = (TextBox) sender;

    if (String.IsNullOrWhitespace(txt.Text) ||
        (decimal.TryParse(txt.Text, out result) && result == 0M))
    {
        txt.Text = "0.00";
    }
}

【讨论】:

    【解决方案2】:
    private void txtOvertimeHours_TextChanged(object sender, EventArgs e)
    {
        ZeroOutTextBox(txtOvertimeHours);
    }
    
    private void txtAllowance_TextChanged(object sender, EventArgs e)
    {
        ZeroOutTextBox(txtAllowance);
    }
    
    private void ZeroOutTextBox(Textbox txt)
    {
        if (txt.Text.Length <= 0 ||
            txt.Text == null ||
            txt.Text == "0.00" ||
            txt.Text == "0" ||
            txt.Text == "0.0")
        {
            txt.Text = "0.00";
        }
    }
    

    【讨论】:

    • 如果所有事件处理程序方法都完全相同,那么@JohnSaunders 的答案会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多