Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Everyone...
I am creating a project where i need to convert text box value into date time every time i have faced an error.. below is my code.

What I have tried:

C#
public int Validate_DOB()
   {
       DateTime dt = DateTime.Parse(txt_DOB.Text);//error occured at this line of code
       int Validate = DateTime.Now.Year - dt.Year;
       return Validate;
   }
Posted
Updated 20-Dec-16 18:14pm

Hi Aamir,

The error is clear from the error msg - the value in the text box is not a datetime. You can use TryParse() as Peter suggested. Or you can catch a FormatException to let the user know about the problem at runtime.
C#
try
{
    DateTime dt = DateTime.Parse(txt_DOB.Text);//error occured at this line of code
    int Validate = DateTime.Now.Year - dt.Year;
}
catch (FormatException)
{
    MessageBox.Show("This is not a valid date time.");
}
 
Share this answer
 
Comments
Muhammd Aamir 21-Dec-16 0:23am    
Thankx Mehedi Shams for sharing your knowledge .... i have done this with calendar extender now there is no string format error...
Muhammd Aamir 21-Dec-16 0:51am    
Hi Mehedi Shams my function return type is integer how can i show alert message...

public int Validate_DOB() // error here not all code path return a value
{
try
{
DateTime dt = DateTime.Parse(txt_DOB.Text);
int Validate = DateTime.Now.Year - dt.Year;
return Validate;
}
catch (FormatException ex)
{
Response.Write("alert('" + Server.HtmlEncode(ex.ToString()) + "')");
}

}
Mehedi Shams 21-Dec-16 1:09am    
Hi Aamir,

Do you mean you want to display the error as a message box? You can use the following code in the exception block:

ClientScript.RegisterStartupScript(this.GetType(), "App Alert", "alert('This is not a valid date time.');", true);
You should use DateTime.TryParse[^]
Alternatively, consider using a datatimepicker to let users select a date rather than a text box that allow free form text. Check this out: Implement DateTimePicker in ASP.Net using jQuery Plugin[^]
 
Share this answer
 
v3
Comments
Muhammd Aamir 21-Dec-16 0:15am    
Thankx Peter Leow... [^] this sign indicates to which type of parameter
Peter Leow 21-Dec-16 0:17am    
It is link to open a page on a new tab.
Muhammd Aamir 21-Dec-16 0:21am    
Oh great Peter Leow You Solve my problem i use calendar extender in text box and now user can select from calendar extender and can select in a correct formate thankx a lot good job done by you

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