9
Answers

How to find age from Access Database in C# WindowsApplicatio

Mayank Jani

Mayank Jani

7y
291
1
Hi all,
 
Greetings of the day...
 
I have a windows form (C#) and access database. in the database i have details of employees and there is one text field that contains date of birth. when i fetch record from the database, how can i display the age (years only. e.g. 25 Years or 35 Years) in a text box?
 
i have googled enough and there so many options but not the answer. please note that i want to get the answer (the age) based on date from database minus todays year.
 
please see the code below...
 
private void txtEmpNo_Validated(object sender, EventArgs e)
 OleDbDataAdapter SearchEmp = new OleDbDataAdapter("Select EmpFullName, EmpDOB, EmpSex, EmpMobileNumber, EmpCity From Employee Where EmpIDNo='" + txtCaseNo.Text + "'", MyConn);

DataSet dsSearchEmp = new DataSet();
SearchEmp.Fill(dsSearchEmp);

if (dsSearchEmp.Tables[0].Rows.Count > 0)
{
   //How to calculate? i have tryed with int, string, datetime, timespan etc.
   txtEmpAge.text = //What code?
}
}
 
please help.
 
thank you
 
Mayank Jani
Answers (9)
0
Amit Gupta

Amit Gupta

NA 16.5k 25.7k 7y
Try like below
 
  1. // Fetch the dob from the dataset  
  2. var dob = Convert.ToDateTime(dsSearchEmp.Tables[0].Rows[0]["EmpDob"]);  
  3.   
  4. var yOld = DateTime.Now.Year - dob.Year;  
 
 
Accepted
0
Mayank Jani

Mayank Jani

NA 154 3.8k 7y
Hey Amit,
 
it's done. i've done some mistake like an idot. 
 
thank you dear.
 
Mayank Jani
0
Mayank Jani

Mayank Jani

NA 154 3.8k 7y
in Access database > Field Name - EmpDOB.  > Field Type - Text.
you can take any value like 15/05/1995.
0
Amit Gupta

Amit Gupta

NA 16.5k 25.7k 7y
Can you share the value of Empdob and dob?
0
Mayank Jani

Mayank Jani

NA 154 3.8k 7y
Hi Amit,
the updated code runs but every time it shows 0 years.
0
Amit Gupta

Amit Gupta

NA 16.5k 25.7k 7y
Hey Mayank, I had updated my answer. Doesn't it work? Have you tried?
0
Mayank Jani

Mayank Jani

NA 154 3.8k 7y
Nah... please note that i want to get the answer (the age) based on date from database (a date and after extract the birth year) minus todays year. or something else that does exact this as result.
0
Dharmraj Thakur

Dharmraj Thakur

NA 4.1k 61.7k 7y
You can try this...
 
DateTime from = Convert.ToDateTime("01-01-2001");
DateTime to = Convert.ToDateTime("01-01-2009");
Console.Write((((to-from).TotalDays)/12)/30);
 
0
Mayank Jani

Mayank Jani

NA 154 3.8k 7y
Hey Amit, nice to see you again...
 
an error says, 'The as operator must be used with a reference type or nullable type ('System.DateTime' is a non-nullable value type)'

thanks for reply.
 
Mayank Jani