Age Calculator C#

Hemanth B 886 Reputation points
2021-05-22T13:56:38.1+00:00

Hi, I recently made an age calculator using C# Win form application. So I set this "If" code for the application saying that if the Date of Birth is set greater than the Current date, an error message should pop up.

Code:

'if (dtpcurrentdate.Value < dtpdateofbirth.Value) ;
{

                MessageBox.Show("Current date must be greater than Date of Birth. Please Try Again");

            }'

When I run the application, test it and set the Date of Birth greater than the Current date, the error message is popping. But when I set Date of Birth lesser than the current date, the error message still pops up. My aim is that the error should not occur when users set the Date of Birth lesser than the current date and should only pop up if they set it greater than the current date. Please help!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,981 questions
0 comments No comments
{count} votes

Accepted answer
  1. WayneAKing 4,921 Reputation points
    2021-05-25T08:04:28.87+00:00

    if (dtpcurrentdate.Value < dtpdateofbirth.Value);
    {
    MessageBox.Show("Current date must be greater ...");
    }

    If the above is what you actually have in your program,
    then the reason why the MessageBox always appears is
    because you have a semicolon at the end of the if
    statement line. Remove it.

    The semicolon ends the scope of the if statement so
    the code in the block between the braces {...} is
    not part of the conditional and so will always be
    executed.

    • Wayne

2 additional answers

Sort by: Most helpful
  1. Viorel 110.1K Reputation points
    2021-05-22T14:07:27.71+00:00

    Remove the first ';'.


  2. Timon Yang-MSFT 9,571 Reputation points
    2021-05-24T02:55:48.377+00:00

    My guess is that you may have misplaced the two DateTimePickers.

    Try to output the values of two DateTimePickers instead of prompt statements.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.