Click here to Skip to main content
15,299,443 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hii ,

i am getting this error please help me to resolve

What I have tried:

C#
private void dtTmPckrEndDt_CloseUp_1(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(dtTmPckrStartDt.Text) && !string.IsNullOrEmpty(dtTmPckrEndDt.Text))
            {
                DateTime StartDate = DateTime.ParseExact(dtTmPckrStartDt.Text, "dd/MMM/yyyy", CultureInfo.InvariantCulture);
                DateTime EndDate = DateTime.ParseExact(dtTmPckrEndDt.Text, "dd/MMM/yyyy", CultureInfo.InvariantCulture);
                if (StartDate > EndDate)
                {
                    MessageBox.Show("Start Date Must be Less than End Date ");
                    dtTmPckrEndDt.CustomFormat = " ";
                }
            }
        }
Posted
Updated 8-Mar-21 5:04am
v2

You should use: DateTimePicker.Value Property (System.Windows.Forms) | Microsoft Docs[^]

C#
DateTime StartDate = dtTmPckrStartDt.Value;
DateTime EndDate = dtTmPckrEndDt.Value;
   
To add to what Maciej says, don't use DateTime.ParseExact on user provided date strings anyway - you are assuming a format that the user may not be using on his computer, and that can cause your app to crash.
Instead, use DateTime.TryParse which assumes the current user language settings and returns a "success / fail" signal instead of crashing your app with an exception.

But in this case, as Maciej says, use the Value property and you get a guaranteed valid DateTime value directly without any need for conversions at all.
   
Comments
Maciej Los 8-Mar-21 7:24am
   
5ed!
private void dtTmPckrEndDt_CloseUp_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(dtTmPckrStartDt.Text) && !string.IsNullOrEmpty(dtTmPckrEndDt.Text))
{
DateTime StartDate = DateTime.Now;
DateTime EndDate = DateTime.Now;

if (DateTime.TryParseExact(dtTmPckrStartDt.Text, "dd/MMM/yyyy", null, System.Globalization.DateTimeStyles.None, out StartDate) && DateTime.TryParseExact(dtTmPckrEndDt.Text, "dd/MMM/yyyy", null, System.Globalization.DateTimeStyles.None, out EndDate)
{
if (StartDate > EndDate)
{
MessageBox.Show("Start Date Must be Less than End Date ");
dtTmPckrEndDt.CustomFormat = " ";
}
else
{
MessageBox.Show("Invalid Start Or End Date");

}
}
}
}
   
v2

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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