Arbaaz Arbaaz - 1 month ago 19
ASP.NET (C#) Question

String was not recognized as a valid DateTime error

DataTable dt1 = new DataTable();
dt1.Columns.Add("studid",typeof(int));
dt1.Columns.Add("rollno", typeof(int));
dt1.Columns.Add("date", typeof(DateTime));
dt1.Columns.Add("starttime", typeof(string));
dt1.Columns.Add("class", typeof(string));
dt1.Columns.Add("section", typeof(string));
dt1.Columns.Add("subject", typeof(string));

for (int i = 0; i < dt.Rows.Count; i++)
{
dt1.Rows.Add(Convert.ToInt32(dt.Rows[i]["id"]), Convert.ToInt32(dt.Rows[i]["rollno"]), Convert.ToDateTime(txtdate.Text),time.SelectedItem.ToString(), drpclass.SelectedItem.ToString(), drpsection.ToString(), drpsubject.SelectedItem.ToString());
}


I am getting error
"String was not recognized as a valid DateTime"
at
time.SelectedItem.ToString()
even though the datatype of DataTable's column is string.
I applied breakpoint and
09:30:00
is the value i am getting in
time.SelectedItem.ToString()

Answer

what value you have in this field txtdate.Text May be it's causing a problem.

You are doing this

 Convert.ToDateTime(txtdate.Text)

So if TextBox contains different value other than date format. then It will throw an error.

Comments