hi i am using asp.net with c# i get this problem when i try to enter date grater than 12 "String was not recognized as a valid DateTime."

i am using sql server 2005. In the table field is in datetime format.In the procedure its is also taking as datetime.and the codes are

DateTime dob = Convert.ToDateTime(txtdob.Text.ToString().Trim());
rec.Add("dob", dob); rec is a hash table.

and the regional setting short date time :MM/dd/yyyy

please help

hi,

use below way..I think its help you

write
dob.ToShortDateString();

then it will give MM/dd/YYYY formate

DateTime dob = Convert.ToDateTime(txtdob.Text.ToString().Trim());
rec.Add("dob", dob.ToShortDateString());

same problem arrise ,even execution is not go to the second line.its immidiately jump to catch()

Hashtable hs = new Hashtable();
DateTime dt = Convert.ToDateTime(TextBox2.Text);
hs.Add("lakshman", dt.ToShortDateString());

using this above code it is working.....let me know any cooncerns

Hashtable rec = new Hashtable();
DateTime dob = Convert.ToDateTime(txtdob.Text.Trim());
rec.Add("dob", dob.ToShortDateString());
why the second line not executing .i have gave a brak point to see the flow ,but after the first line its jump to catch()

Where you wrote this code?...If you write this code in page load it's not work....Why because when you run the application first it runs the page load....that time we haven't give any value to text box.....

If you write this code in any other event it will work....check this and let me know.....

sir i am using this code in the submit event
not in page load.

 protected void btnSave_Click(object sender, System.EventArgs e)
{
try
{
Hashtable rec = new Hashtable();
 if (txtdob.Text.Length != 0)
                    {
                        DateTime dob = Convert.ToDateTime(txtdob.Text.Trim());
                        rec.Add("dob", dob.ToShortDateString());
                    }
}
catch( Exception ex)
{
lblerror.visible=true;
lbl.text=ex.Message;
}
}
}

Edited 3 Years Ago by Nick Evan: Fixed formatting

IF you write MM/DD/YYYY formate it is not giving any error.....

If you write DD/MM/YYYY formate it is giving error when you convert to datetime....

try this way and let me know

but if i put 7/11/1983 its inserting whats the ploblem.it mean not taking the value grater than 12 in case of date

If text box value is MM/DD/YYYY formae...It is converting to Datetime....

value isDD/MM/YYYY formate it's not converting to datetime.....

Means you have to enter MM/DD/YYYY formate in txtdob.....

now i have changed the regional setting to dd/MM/yyyy and trying to insert 13/11/1987
with the same code .now its showing the error
"Error converting data type nvarchar to datetime." I have seen the execution is going up to the procedure calling but after that is jumps to catch()

This article has been dead for over six months. Start a new discussion instead.