Hello I am working on this code for a hotel reservation. so far I am stuck on the part which requests that fridays and saturdays be charged 150 instead of the 120 usual cost per night.
I have dateTime variables for the arrival date and departure date and a timeSpan variable for the duration of the stay. my thought was to step through each day of the timeSpan variable and for each occurance of the DayOfWeek.Friday and DayOfWeek.Saturday I was going to add 30 dollars (the additional cost for a weekend night) to a variable weekendCost which i would then add to the total cost.

I know I am probably going about this wrong, my teacher wanted us to use a while loop, but I am not sure how to get that to work.

any help would be greatly appreciated.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Reservations
{
    public partial class frmReservations : Form
    {
        public frmReservations()
        {
            InitializeComponent();
        }


        //public bool IsValidData()
        // {
        //      return

        //  }

        public bool IsPresent(TextBox textBox, string name)
        {
            if (textBox.Text == "")
            {
                MessageBox.Show(name + " is a required field.", "Entry Error");
                textBox.Focus();
                return false;
            }
            return true;
        }

        //public bool IsDateTime(TextBox textBox, string name)
        //{

        //}

        //public bool IsWithinRange(TextBox textBox, string name,
        //    DateTime min, DateTime max)
        //{

        //}

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            DateTime dtArrivalDate;
            DateTime.TryParse(txtArrivalDate.Text, out dtArrivalDate);

            DateTime dtDepartureDate;
            DateTime.TryParse(txtDepartureDate.Text, out dtDepartureDate);

            TimeSpan tsDuration = dtDepartureDate.Subtract(dtArrivalDate);

            int costPerNight = 120;
            for (DateTime date = dtArrivalDate; date <= dtDepartureDate; date = date.AddDays(1))

            {
                DayOfWeek dw = date.DayOfWeek;
                string days = dw.ToString();
                int weekendCost = 0;

                if (dw == DayOfWeek.Friday || dw == DayOfWeek.Saturday)
                {
                    weekendCost = weekendCost + 30;
                    dw ++;

                    int totalCost = tsDuration.Days * costPerNight + weekendCost;
                    int avgPricePerNight = (tsDuration.Days * costPerNight + weekendCost) / tsDuration.Days;

                    txtNights.Text = tsDuration.Days.ToString("n");
                    txtTotalPrice.Text = totalCost.ToString("n");
                    txtAvgPrice.Text = avgPricePerNight.ToString("n");
                }
             }



            }




        private void frmReservations_Load(object sender, EventArgs e)
        {
                txtArrivalDate.Text = DateTime.Today.ToString("d");
                txtDepartureDate.Text = DateTime.Today.AddDays(3).ToString("d");


        }



}
}

Here's a quick test i created which you can work from.

    double TotalCost = 0;
    DateTime CheckinDate = dateTimePicker1.Value;
    DateTime CheckOutDate = dateTimePicker2.Value;

    while (CheckinDate.ToShortDateString() != CheckOutDate.ToShortDateString())
    {
      if (CheckinDate.DayOfWeek.ToString() == Day.Friday.ToString() || CheckinDate.DayOfWeek.ToString() == Day.Saturday.ToString())
      {
        TotalCost = TotalCost + 150;
      }
      else
      {
        TotalCost = TotalCost + 120;
      }
      CheckinDate = CheckinDate.AddDays(1);
     }

Hope this helps

Edited 3 Years Ago by Fenrir()

Thanks that definitely did help, I am still getting an error under bothe dateTimePicker values saying that the name does not exist in the current context. also the other error i'm getting is for the dtDepartureDate saying that it does not exist in the current context i think it may be a formatting error but i'm not sure- sorry newbie here.. also not sure if I am validating that the values entered are indeed in the mm/dd/yyyy format. any help there would be appreciated this is the updated code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Reservations
{
    public partial class frmReservations : Form
    {
        public frmReservations()
        {
            InitializeComponent();
        }


        public bool IsValidData()
         {
             return
                 IsPresent(txtArrivalDate, "Arrival Date") &&
                 IsDateTime(txtArrivalDate, "Arrival Date") &&
                 IsWithinRange(txtArrivalDate, "Arrival date", DateTime.Today, DateTime.Today.AddYears(5)) &&

                 IsPresent(txtDepartureDate, "Departure Date") &&
                 IsDateTime(txtDepartureDate, "Departure Date") &&
                 IsWithinRange(txtDepartureDate, "Departure date", DateTime.Today, DateTime.Today.AddYears(5));


          }

        public bool IsPresent(TextBox textBox, string name)
        {
            if (textBox.Text == "")
            {
                MessageBox.Show(name + " is a required field.", "Entry Error");
                textBox.Focus();
                return false;
            }
            return true;
        }

        public bool IsDateTime(TextBox textBox, string name)
        {
            DateTime dtArrivalDate;
            if (DateTime.TryParse(txtArrivalDate.Text, out dtArrivalDate))
            {
                return true;
            }
            else
            {
                MessageBox.Show(name + " must be entered in the following format mm/dd/yyyy");
                textBox.Focus();
                return false;
            }

            DateTime dtDepartureDate;
            if (DateTime.TryParse(txtDepartureDate.Text, out dtDepartureDate))
            {
                return true;
            }
            else
            {
                MessageBox.Show(name + " must be entered in the following format mm/dd/yyyy");
                textBox.Focus();
                return false;
            }
        }

        public bool IsWithinRange(TextBox textBox, string name,
            DateTime min, DateTime max)
        {
            DateTime arDate = Convert.ToDateTime(txtArrivalDate);
            DateTime dpDate = Convert.ToDateTime(txtDepartureDate);
            if (arDate < min || arDate > max)
            {
                MessageBox.Show(arDate + " must be entered in a mm/dd/yyyy format and must be from today to 5 years, from today.");
                txtArrivalDate.Focus();
                return false;
            }
            if (dpDate < min || dpDate > max)
            {
                MessageBox.Show(dpDate + " must be entered in a mm/dd/yyyy format and must be from today to 5 years, from today.");
                txtDepartureDate.Focus();
                return false;
            }
                return true;

        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsValidData())
                {
                    DateTime dtArrivalDate = Convert.ToDateTime(txtArrivalDate.Text);
                    DateTime dtDepartureDate = Convert.ToDateTime(txtDepartureDate.Text);


                    TimeSpan tsDuration = dtDepartureDate.Subtract(dtArrivalDate);
                    double TotalCost = 0;
                    DateTime CheckInDate = dateTimePicker1.Value;
                    DateTime CheckOutDate = dateTimePicker2.Value;

                    while (CheckInDate.ToShortDateString() != CheckOutDate.ToShortDateString())
                    {
                        if (CheckInDate.DayOfWeek.ToString() == Day.Friday.ToString() || CheckInDate.DayOfWeek.ToString() == Day.Saturday.ToString())
                        {
                            TotalCost = TotalCost + 150;
                        }
                        else
                        {
                            TotalCost = TotalCost + 120;
                        }
                        CheckInDate = CheckInDate.AddDays(1);
                    }


                    double avgPricePerNight = (TotalCost / tsDuration.Days);

                    txtNights.Text = tsDuration.Days.ToString("n");
                    txtTotalPrice.Text = TotalCost.ToString("n");
                    txtAvgPrice.Text = avgPricePerNight.ToString("n");


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "/n/n" +
                    ex.GetType().ToString() + "/n" +
                    ex.StackTrace, "Exception");
             }



        }


        private void frmReservations_Load(object sender, EventArgs e)
        {
            txtArrivalDate.Text = DateTime.Today.ToString("d");
            txtDepartureDate.Text = DateTime.Today.AddDays(3).ToString("d");


        }
    }
}

Thanks!!

Instead of using text boxes why dont you just use the datetimepicker from the toolbox? I used 2 datetimepickers on a form so they won't exist in your application unless you create them. As for dtDeparture date make sure you declare it somewhere where all your methods can access it if multiple methods use it. Try moving your variable declarations to the top of your method and set their values where they are declared now.

Oh I wasn't sure what that was- that would be nice but my teach is anal and I know she would be upset i didn't do it like it was suppose to be done- she doesn't give much advice this is what she posted with the start of a form.

In this exercise, you’ll add code that calculates the number of nights, total price, and average price for a reservation based on the arrival and departure dates the user enters.

Open the project and implement the calculation

Add code to get the arrival and departure dates the user enters when the user clicks the Calculate button. Then, calculate the number of days between those dates, calculate the total price based on a price per night of $120, calculate the average price per night, and display the results.

Test the application to be sure it works correctly. At this point, the average price will be the same as the nightly price.

Enhance the way the form works

Add an event handler for the Load event of the form. This event handler should get the current date and three days after the current date and assign these dates to the Arrival Date and Departure Date text boxes as default values. Be sure to format the dates as shown above.

Modify the code so Friday and Saturday nights are charged at $150 and other nights are charged at $120. One way to do this is to use a while loop that checks the day for each date of the reservation.

Test the application to be sure that the default dates are displayed correctly and that the totals are calculated correctly.

Add code to validate the dates

Uncomment the IsDateTime method and then add code to check that the arrival and departure dates are valid dates.

Uncomment the IsWithinRange method and then add code to check that the arrival and departure dates are within a range that includes the minimum and maximum dates that are passed to it.

Uncomment the IsValidData method and then add code that uses the IsPresent, IsDateTime, and IsWithinRange methods to validate the arrival and departure dates. These dates should be in a range from the current date to five years after the current date.

Add code that uses the IsValidData method to validate the arrival and departure dates. In addition, add code to check that the departure date is after the arrival date.

Test the application to be sure the dates are validated properly.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Reservations
{
    public partial class frmReservations : Form
    {
        public frmReservations()
        {
            InitializeComponent();
        }


        public bool IsValidData()
         {
             return
                 IsPresent(txtArrivalDate, "Arrival Date") &&
                 IsDateTime(txtArrivalDate, "Arrival Date") &&
                 IsWithinRange(txtArrivalDate, "Arrival date", DateTime.Today, DateTime.Today.AddYears(5)) &&

                 IsPresent(txtDepartureDate, "Departure Date") &&
                 IsDateTime(txtDepartureDate, "Departure Date") &&
                 IsWithinRange(txtDepartureDate, "Departure date", DateTime.Today, DateTime.Today.AddYears(5));


          }

        public bool IsPresent(TextBox textBox, string name)
        {
            if (textBox.Text == "")
            {
                MessageBox.Show(name + " is a required field.", "Entry Error");
                textBox.Focus();
                return false;
            }
            return true;
        }

        public bool IsDateTime(TextBox textBox, string name)
        {
            DateTime validDate = Convert.ToDateTime(textBox.Text);
            if (string.IsNullOrEmpty(textBox.Text) || !DateTime.TryParse(textBox.Text, out validDate))
            {
                MessageBox.Show(name + " Invalid date!",
                    "Entry Error");
                textBox.Focus();
                return false;

            }
            else
            {
                return false;
            }


        }

        public bool IsWithinRange(TextBox textBox, string name,
            DateTime min, DateTime max)
        {
            DateTime arDate = Convert.ToDateTime(txtArrivalDate);
            DateTime dpDate = Convert.ToDateTime(txtDepartureDate);
            if (arDate < min || arDate > max)
            {
                MessageBox.Show(arDate + " must be entered in a mm/dd/yyyy format and must be from today to 5 years, from today.");
                txtArrivalDate.Focus();
                return false;
            }
            if (dpDate < min || dpDate > max)
            {
                MessageBox.Show(dpDate + " must be entered in a mm/dd/yyyy format and must be from today to 5 years, from today.");
                txtDepartureDate.Focus();
                return false;
            }
                return true;

        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsValidData())
                {




                    DateTime dtArrivalDate = Convert.ToDateTime(txtArrivalDate.Text);
                    DateTime dtDepartureDate = Convert.ToDateTime(txtDepartureDate.Text);
                    TimeSpan tsDuration = dtDepartureDate.Subtract(dtArrivalDate);


                    double TotalCost = this.CalculateTotalCost(dtArrivalDate,dtDepartureDate,tsDuration);
                 //   double AvgPricePerNight = this.CalculateAvgCost(TotalCost, dtArrivalDate, dtDepartureDate);
                    txtNights.Text = tsDuration.Days.ToString("n");
                    txtTotalPrice.Text = TotalCost.ToString("n");
                    txtAvgPrice.Text = AvgPricePerNight.ToString("n");

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "/n/n" +
                    ex.GetType().ToString() + "/n" +
                    ex.StackTrace, "Exception");
            }

        }

        private double CalculateTotalCost(DateTime dtArrivalDate, DateTime dtDepartureDate, TimeSpan tsDuration)
        {
            double TotalCost = 0;




            while (dtArrivalDate.ToShortDateString() != dtDepartureDate.ToShortDateString())
            {
                if (dtArrivalDate.DayOfWeek.ToString() == Day.Friday.ToString() || dtArrivalDate.DayOfWeek.ToString() == Day.Saturday.ToString())
                {
                    TotalCost = TotalCost + 150;
                }
                else
                {
                    TotalCost = TotalCost + 120;
                }
                dtArrivalDate = dtArrivalDate.AddDays(1);
            } return TotalCost;



        }

       // private double CalculateAvgCost(double TotalCost, DateTime dtArrivalDate, DateTime dtDepartureDate)
       // {

            //    DateTime daysInStay = dtDepartureDate.Subtract(dtArrivalDate);
            //    double intDaysInsStay = Convert.ToDouble.daysInStay;

           //     AvgPricePerNight = TotalCost / (dtDepartureDate.Subtract(dtArrivalDate)
           //     return AvgPricePerNight;
     //   }
        private void frmReservations_Load(object sender, EventArgs e)
        {
            txtArrivalDate.Text = DateTime.Today.ToString("d");
            txtDepartureDate.Text = DateTime.Today.AddDays(3).ToString("d");


        }


    }
}

thats the code i have so far, not sure if i'm making progress or making it worse. She wants us to validate the date by doing the isValid method and then if it passes each of those it should go on to do the calculations. I'm not sure how to make it so the message displays the particular exception that is being thrown.
any more help would be appreciated, i'm not sure maybe i need to make an array to step through each day in the timespan.
or maybe a stringbuilder??

okay this is where I am at, i don't have any errors but I can't even get the results on the resulting text boxes

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Reservations
{
    public partial class frmReservations : Form
    {
        public frmReservations()
        {
            InitializeComponent();
        }

        // method to check valid data
        public bool IsValidData()
         {
             return
                 //chcecks for present, dateTime, within range for arrival and departure
                 IsPresent(txtArrivalDate, "Arrival Date") &&
                 IsDateTime(txtArrivalDate, "Arrival Date") &&
                 IsWithinRange(txtArrivalDate, "Arrival date", DateTime.Today, DateTime.Today.AddYears(5)) &&

                 IsPresent(txtDepartureDate, "Departure Date") &&
                 IsDateTime(txtDepartureDate, "Departure Date") &&
                 IsWithinRange(txtDepartureDate, "Departure date", DateTime.Today, DateTime.Today.AddYears(5));

          }

        // method to check if present
        public bool IsPresent(TextBox textBox, string name) 
        {
            if (textBox.Text == "")
            {
                MessageBox.Show(name + " is a required field.", "Entry Error");
                textBox.Focus();
                return false;
            }
            return true;
        }

        //method to check if data is entered in dateTime format
        public bool IsDateTime(TextBox textBox, string name)
        {
            DateTime validDate = Convert.ToDateTime(textBox.Text);
            if (string.IsNullOrEmpty(textBox.Text) || !DateTime.TryParse(textBox.Text, out validDate))
            {
                MessageBox.Show(name + " Invalid date!",
                    "Entry Error");
                textBox.Focus();
                return false;

            }
            else
            {
                return true;
            }
        }

        //method to ensure data is within range
        public bool IsWithinRange(TextBox textBox, string name,
            DateTime min, DateTime max)
        {
            DateTime arDate = Convert.ToDateTime(txtArrivalDate);
            DateTime dpDate = Convert.ToDateTime(txtDepartureDate);
            if (arDate < min || arDate > max)
            {
                MessageBox.Show(arDate + " must be entered in a mm/dd/yyyy format and must be from today to 5 years, from today.");
                txtArrivalDate.Focus();
                return false;
            }
            if (dpDate < min || dpDate > max)
            {
                MessageBox.Show(dpDate + " must be entered in a mm/dd/yyyy format and must be from today to 5 years, from today.");
                txtDepartureDate.Focus();
                return false;
            }
                return true;

        }

        //method to exit the form
        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        //private method to calculate cost, ave price, and display the data
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsValidData())
                {


                    DateTime dtArrivalDate = Convert.ToDateTime(txtArrivalDate.Text);
                    DateTime dtDepartureDate = Convert.ToDateTime(txtDepartureDate.Text);
                    TimeSpan tsDuration = dtDepartureDate.Subtract(dtArrivalDate);


                    double TotalCost = this.CalculateTotalCost(dtArrivalDate,dtDepartureDate,tsDuration);
                    double AvgPricePerNight = this.CalculateAvgCost(TotalCost, dtArrivalDate, dtDepartureDate);
                    txtNights.Text = tsDuration.Days.ToString("n");
                    txtTotalPrice.Text = TotalCost.ToString("n");
                    txtAvgPrice.Text = AvgPricePerNight.ToString("n");


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "/n/n" +
                    ex.GetType().ToString() + "/n" +
                    ex.StackTrace, "Exception");
            }

        }

        //method to calculate total cost
        private double CalculateTotalCost(DateTime dtArrivalDate, DateTime dtDepartureDate, TimeSpan tsDuration)
        {
            double TotalCost = 0;




            while (dtArrivalDate.ToShortDateString() != dtDepartureDate.ToShortDateString())
            {
                if (dtArrivalDate.DayOfWeek.ToString() == Day.Friday.ToString() || dtArrivalDate.DayOfWeek.ToString() == Day.Saturday.ToString())
                {
                    TotalCost = TotalCost + 150;
                }
                else
                {
                    TotalCost = TotalCost + 120;
                }
                dtArrivalDate = dtArrivalDate.AddDays(1);

            } return TotalCost;



        }

        //method to calculate avecost
        private double CalculateAvgCost(double TotalCost, DateTime dtArrivalDate, DateTime dtDepartureDate)
        {
               int duration = Convert.ToInt32(Math.Ceiling(Math.Abs(dtArrivalDate.Subtract(dtDepartureDate).TotalDays))) + 1;

                double AvgPricePerNight = TotalCost / duration;



               return AvgPricePerNight;
        }

        //load current date and 3 days in advance
        private void frmReservations_Load(object sender, EventArgs e)
        {
            txtArrivalDate.Text = DateTime.Today.ToString("d");
            txtDepartureDate.Text = DateTime.Today.AddDays(3).ToString("d");


        }


    }
}

Edited 3 Years Ago by Judson

This article has been dead for over six months. Start a new discussion instead.