How to enter a default value when a TextBox is empty

Marek picture Marek · Jul 28, 2013 · Viewed 27.8k times · Source

I have this method which SUM values in those textboxes, I wanted to improve it so if any of these textboxes is empty I would like to insert into it "0" but I didn't knew where to and what exactly put to make it work like I want. I have wondered about this for quiet long time, would someone suggest me something please ?

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

Thanks everyone for their help and time.

Answer

terrybozzio picture terrybozzio · Jul 28, 2013

You can make one textbox validated event (because if empty you just need to insert 0 and not retain focus),and subscribe all other textboxes to that textbox validated event.

For example: you have 5 textboxes subscribe (by clicking for example textbox1 properties window|events and double-click validated), and for the other textboxes subscribe their validated event to that one, then inside it put this:

private void textBox1_Validated(object sender, EventArgs e)
{
    if (((TextBox)sender).Text == "")
    {
        ((TextBox)sender).Text = "0";
    }
}