Search code examples
c#winformsevent-driven

Text box is null and having the program detecting that


Hi i am new to event driven programming and would love if i could have some help.

I have been set some work and i am getting through it ok but there is one downside, in my code below: i have a text box that if text is entered then it would add 2.00, however its constantly adding 2.00 to the total.

I have tried to use an if statement however that didn't work and I am getting really annoyed with the whole thing.

The code isn't complete as i want to do this as much as possible by myself.

decimal sizeCost = 0.00m;
const decimal extraSmall = 4.50m;
const decimal Small = 5.00m;
const decimal meduim = 5.50m;
const decimal large = 6.00m;
const decimal extraLarge = 7.00m;

string red;
string blue;
string white;
string green;
string purple;
string yellow;
string colour;

decimal fabCost = 0.00m;
const decimal cotton = 1.00m;
const decimal lycra = 2.50m;

int quanty = 0;
const decimal printingCost = 2.00m;

decimal cost = 0;
decimal totalCost1 = 0;
decimal totalCost = 0;
string surname = "";

private void buttonOrder_Click(object sender, EventArgs e)
{
    totalCost = sizeCost * quanty; 
    totalCost1 = fabCost * quanty;

   //fix this
   if (string.IsNullOrWhiteSpace(textBox1.Text))
   {
      cost = cost - 2.00m;
   }

   cost = fabCost + sizeCost + printingCost;
   labelDisplayCost.Text = cost.ToString("c");
   MessageBox.Show("The total cost is" + cost );
}

private void numericUpDownQuant_ValueChanged(object sender, EventArgs e)
{
    quanty = Convert.ToByte(numericUpDownQuant.Value);
}

Solution

  • This is always going to fire as it will always be true

    //fix this
     if (string.IsNullOrWhiteSpace(textBox1.Text))
     {
        cost = cost - 2.00m;
     }
    

    Would this not need to be

    //fix this
     if (!string.IsNullOrWhiteSpace(textBox1.Text))
     {
        cost = cost - 2.00m;
     }
    

    The ! would reverse the command to check it does have text, and then you can add the 2.00 to the cost.

    This would then be the equivalent of saying

    if(true)
    {
    //do something
    }