Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all, got a slight problem when checking to see if the date is a proper date, im checking to see if the date is no more than 31 days and also to check if the "To date" is greater than the "From Date" those 2 functions work but now i got to check if those dates are valid so you cant for example say "2012/10/45",

how can i do this my code for the date is as follows
C#
{
        DateTime dt = Convert.ToDateTime(TextBox1.Text);
        DateTime dta = Convert.ToDateTime(TextBox2.Text);
        TimeSpan pp = dta - dt;
        int days = pp.Days;

        string s = TextBox1.Text;
        string t = TextBox2.Text;

        DateTime theDateA = DateTime.Parse(s);
        DateTime theDateB = DateTime.Parse(t);

        if (theDateB > theDateA)
        {
            if (days > 31)
            {
                TextBox1.BackColor = System.Drawing.Color.Red;
                TextBox2.BackColor = System.Drawing.Color.Red;
                date_Error_cell.Text = "Select a DATE NOT more than 31 days";
                date_Error_cell.Attributes.Add("style", "font-weight:bold; text-align:center; font-family:Calibri; color:Red; font-size:large;");
                Monthly_Spend();
                label();
            }
            else
            {

                TextBox1.BackColor = System.Drawing.Color.White;
                TextBox2.BackColor = System.Drawing.Color.White;
                date_Error_cell.Text = "";
                bind_grid();
                Monthly_Spend();
            }
        }
        else
        {
            date_Error_cell.Text = "Select a VALID date";
        }
    }
Posted
Updated 14-Oct-12 21:03pm
v2
Comments
Himanshu Yadav 15-Oct-12 3:24am    
Put try and catch block ones if any one enter wrong date it will exception and can be caught in catch block.

Hope this will help
n.podbielski 15-Oct-12 3:51am    
Never ever do that! Its bad design and bad pattern. And it's pain in the ass to debug application with try catch code style!

Use DateTime.TryParse[^] or DateTime.TryParseExact[^] methods instead of Parse - they do the conversion if they can, and return a bool value to indicate success or failure without throwing exceptions at all.
 
Share this answer
 
In your textbox use regular expression for date check;

with the below validation expression

Copy Code(0[1-9]|[12][0-9]|3[01]).(0[1-9]|1[012]).\d{4}
 
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