Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have one MaskedTextBox, One textbox and one Button. I need to calculate the age of a child in months. See the code bellow;

I need that when i type the date of birth of a child into the MaskedTextBox, and click the button the result should display in the textbox (in months)

---- my problem is that, When i run the code and type the dob of a child the dob of a child is copying exactly what is written on the MaskedTextBox.

Soo please help me

What I have tried:

C#
private void AGE_CALC_TextChanged(object sender, EventArgs e)
{
	try
	{
		if (AGE_FINAL.Text.Length >= 1)
		{
			if (Convert.ToDateTime(DATEBIRTH.Text).Year == 1908)
			{
				double age_days = (System.DateTime.Now -
                                  Convert.ToDateTime(DATEBIRTH.Text)).TotalDays;

				//(EndDate - StartDate).TotalDays
				//MessageBox.Show(age_days.ToString());
				if (age_days > 183 && age_days <= 1825)
				{
					CHILDAGE.Text = "1";
					CHILDAGE.Enabled = false;
				}
				else
				{
					CHILDAGE.Text = "2";
					CHILDAGE.Enabled = false;
				}
			}
			else if (Convert.ToDateTime(DATEBIRTH.Text).Year != 1908)
			{
				double age_days = (System.DateTime.Now -
                                  Convert.ToDateTime(DATEBIRTH.Text)).TotalDays;

				//(EndDate - StartDate).TotalDays
				//MessageBox.Show(age_days.ToString());
				if (age_days > 183 && age_days <= 1825)
				{
				   // MessageBox.Show(age_days.ToString());
					CHILDAGE.Text = "1";
					CHILDAGE.Enabled = false;
					SEX.Focus();
				}
				else
				//else if (age_days <= 183 && age_days > 1825)
				{
					// MessageBox.Show(age_days.ToString());
					CHILDAGE.Text = "2";
					CHILDAGE.Enabled = false;
					SEX.Focus();
				}
			}
		}
	}

	catch
	{
		MessageBox.Show("Please put in a date of birth if known", "ZTDT");
	}
}
Posted
Updated 24-Aug-22 1:46am
v2
Comments
Richard Deeming 24-Aug-22 11:43am    
That code is very confused. For example, why do you have two almost identical blocks, with the only difference being that you don't focus the "sex" control if the DoB is in 1908?

And why does your else block then test that the year is not 1908, given that you already know it isn't because the if block didn't execute?

And why are you calling Convert.ToDateTime so many times, rather than storing the result in a local variable and reusing it?

And if you want to calculate the age in months, why are you calculating the difference between the DoB and the current date in days?

Have a look here: Working with Age: it's not the same as a TimeSpan![^] - it has code for working with ages.
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900