Search code examples
c#variablesinputgloballocal

How would I get the code to use a different variable when the user does not input anything into a text box?


I'm making a mileage calculator for a college project. I want to make sure that the program uses the global variable if the user doesn't input anything within the text box. Example: if the user doesn't input anything into the costPerLitre box then use the globals.averageCostPerLitre


        public static class globals
        {
            public const double averageCostPerLitre = 1.25;
            public const double averageMilesPerGallon = 50.5;
            public const int averageGallonsInTank = 14;
            public const int highestSpeed = 70;
            public const int lowestSpeed = 30;
        }
        
        private void button2_Click(object sender, EventArgs e)
        {

            double costPerLitre = Convert.ToDouble(textBox5.Text);
            double milesPerGallon = Convert.ToDouble(textBox6.Text);
            double routeMiles = Convert.ToInt32(textBox7.Text);
            double numberOfGallons = Convert.ToInt32(textBox8.Text);

            if (costPerLitre == 0)
            {
                costPerLitre = globals.averageCostPerLitre;
            }
            else if (milesPerGallon == 0)
            {
                milesPerGallon = globals.averageMilesPerGallon;
            }
            else if (numberOfGallons == 0)
            {
                numberOfGallons = globals.averageGallonsInTank;
            }
            else
            {
                // Do nothing
            }

My problem is that when the code is ran and nothing is input, then it stops and breaks. I have no idea on how to fix this issue.

Full code:

https://i.sstatic.net/biY5d.png


Solution

  • Error is on every row like double costPerLitre = Convert.ToDouble(textBox5.Text) because when text is empty you can't convert it to double!

    So you could amend every row with:

    double costPerLitre = string.IsNullOrEmpty(textBox5.Text)  
        ? globals.averageCostPerLitre  
        : Convert.ToDouble(textBox5.Text);