c# - check if age is <18 datepicker wpf -
i'm making application user has more 18. if he/she less 18 messagebox
appears saying "under age". i'm using datepicker
to select users d.o.b. problem i'm not entirely sure on how code gave go looking @ tutorials tutorials seem datetimepickers
.
my code follows:
xaml
<datepicker horizontalalignment="center" name="dpkdob" grid.column="1" verticalalignment="top" grid.row="1" />
xaml.cs
int age = datetime.today.year - tbkdob.value.year; if (age < 18) { messagebox.show("under age"); }
i have tested in visual studio. please find below working code :
xaml :
<datepicker horizontalalignment="center" name="dpkdob" grid.column="1" verticalalignment="top" grid.row="1" selecteddatechanged="dpkdob_selecteddatechanged"/>
xaml.cs :
public mainwindow() { initializecomponent(); } private void dpkdob_selecteddatechanged(object sender, selectionchangedeventargs e) { var ageinyears = getdifferenceinyears(dpkdob.selecteddate.value, datetime.today); if (ageinyears < 18) { messagebox.show("under age"); } } int getdifferenceinyears(datetime startdate, datetime enddate) { return (enddate.year - startdate.year - 1) + (((enddate.month > startdate.month) || ((enddate.month == startdate.month) && (enddate.day >= startdate.day))) ? 1 : 0); }
Comments
Post a Comment