如何在TextBox为空时输入默认值

本文关键字:输入 默认值 TextBox | 更新日期: 2023-09-27 18:25:07

我有这个methodSUM在这些textboxes中取值,我想改进它,所以如果这些textboxes中的任何一个是empty,我想插入"0",但我不知道在哪里,确切地放什么,让它像我想要的那样工作。我想了很久了,有人能给我推荐点什么吗?

void vypocti_naklady()
    {
        double a, b,c,d,e,f,g,h;
        if (
            !double.TryParse(p_ub_s.Text, out a) ||
            !double.TryParse(p_poj_s.Text, out b) ||
            !double.TryParse(p_jin_s.Text, out c) ||
            !double.TryParse(p_dop_s.Text, out d) ||
            !double.TryParse(p_prov_s.Text, out e) ||
            !double.TryParse(p_pruv_s.Text, out f) ||
            !double.TryParse(p_rez_s.Text, out g) ||
            !double.TryParse(p_ost_s.Text, out h) 
        )
        {
            naklady.Text = "0";
            return;
        }
        naklady.Text = (a+b+c+d+e+f+g+h).ToString();
    }

感谢大家的帮助和时间。

如何在TextBox为空时输入默认值

您可以创建一个文本框验证事件(因为如果为空,您只需要插入0而不保留焦点),并将所有其他文本框订阅到该文本框验证的事件。

例如:您有5个文本框订阅(例如,通过单击textbox1属性窗口|事件并双击validated),其他文本框将其已验证的事件订阅到该文本框,然后在其中放入:

private void textBox1_Validated(object sender, EventArgs e)
{
    if (((TextBox)sender).Text == "")
    {
        ((TextBox)sender).Text = "0";
    }
}
private double GetValue(string input)
{
  double val;
  if(!double.TryParse(input,out val))
  {
    return val;
  }
  return 0;
}
var sum = this.Controls.OfType<TextBox>().Sum(t => GetValue(t.Text));

试试上面的。只需在文本框的父级上运行OfType(父级可能是表单本身)

这将把任何无效输入计数为0

试试这个:

// On the textboxes you want to monitor, attach to the "LostFocus" event.
textBox.LostFocus += textBox_LostFocus;

这会监视TextBox何时失去焦点(已从中单击)。当它有,然后运行这个代码:

static void textBox_LostFocus(object sender, EventArgs e) {
    TextBox theTextBoxThatLostFocus = (TextBox)sender;
    // If the textbox is empty, zeroize it.
    if (String.IsNullOrEmpty(theTextBoxThatLostFocus.Text)) {
        theTextBoxThatLostFocus.Text = "0";
    }
}

如果效果良好,请观看TextBox.LostFocus事件。然后,当使用单击离开框时,它将运行textBox_LostFocus。如果TextBox为空,则我们将该值替换为零。

另一种选择不是直接使用TextBox文本并对其进行解析,而是数据绑定到一个属性并使用它们。Binding本身将进行解析和验证,使您的变量始终保持干净并可供使用。

public partial class Form1 : Form
{
    // Declare a couple of properties for receiving the numbers
    public double ub_s { get; set; }
    public double poj_s { get; set; }   // I'll cut all other fields for simplicity
    public Form1()
    {
        InitializeComponent();
        // Bind each TextBox with its backing variable
        this.p_ub_s.DataBindings.Add("Text", this, "ub_s");
        this.p_poj_s.DataBindings.Add("Text", this, "poj_s");
    }
    // Here comes your code, with a little modification
    private void vypocti_naklady()
    {
       if (this.ub_s == 0 || this.poj_s == 0 /*.......*/)
       {
           naklady.Text = "0";
           return;
       }
       naklady.Text = (this.ub_s + this.poj_s).ToString();
    }
}

您只需要处理已经安全地键入为double的属性,而忘记格式化和解析。您可以通过将所有数据移动到ViewModel类并将逻辑放在那里来改进这一点。理想情况下,您也可以通过对输出TextBox进行数据绑定来将相同的想法应用于它,但要实现这一点,您必须实现INotifyPropertyChanged,以便绑定知道何时更新UI。