Tuesday, May 10, 2016

Program 7: Windows Form Application: Accept DOB & Display age.

  1. Open Visual studio 2013.
  2. On the menu bar, choose File, New, and Project. Choose Programming language as Visual C#. In the templates list, choose the Windows Forms Application icon.
  3. Name the project as AgeCalculator and specify the address of your folder.
  4. In the main window design the form as shown below and set the properties.

    Windows Form: Age calculator
    5.  In the btnCalc_Click method write the following code.
    private void btnCalc_Click(object sender, EventArgs e)
     
    {
     
    DateTime bdate = dtDOB.Value;
     
    DateTime cdate = dtCurrentDate.Value;
     
    MessageBox.Show("Your Age is " + fCalcAge(cdate, bdate).ToString());
     
    }

    In the above code, we have accepted DOB as well as Current date using two DateTime Picker control. The difference between currentdate and DOB is calculated and presented as age. The same task can be done with only one DateTimePicker control to accept the DOB. The current date will be system date which can accessed through code. See the code below. The following method is a user defined method and is declared as public.
    6. Write the following code in the fCalcAge(cdate, bdate) method. This is the user defined method and is declared as public.
public long fCalcAge(System.DateTime CurrentDate, System.DateTime
                                                                                                           BirthDate)
     {
        long age = 0;

        System.TimeSpan ts = CurrentDate.Subtract(BirthDate);
       
        age = (long)(ts.Days / 365);

        return age;
     }

7. Execute the program..see the result.

Enjoy Programming...

No comments:

Post a Comment