我只是想知道是否可以简化这些代码?我有多个带有相同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";
}
}
//等等
答案 0 :(得分: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";
}
}
答案 1 :(得分:0)
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";
}
}