-2

my dropdown is like this
my dropdown is like this

here iam storing selected value of dropdown into variable of type 'TimeSpan' and saving in database. But it gives exception: 'String was not recognized as a valid TimeSpan.' my database fieldtype is also Time(7)

 DateTime start_time = DateTime.ParseExact(starttime.SelectedItem.Text, "hh:mm tt", CultureInfo.InvariantCulture);
 TimeSpan stt = start_time.TimeOfDay;
SqlCommand com = new SqlCommand("INSERT INTO IvrDatas starttime values @starttime",conn);
com.Parameters.AddWithValue("@starttime", stt)

Please help me out in this matter.

ahmed
  • 39
  • 1
  • 8
  • How about reading the documentation for `TimeSpan.Parse`? – Uwe Keim Apr 12 '16 at 15:32
  • Yeah i did but couldn't find solution for my code – ahmed Apr 12 '16 at 15:34
  • How can a single time value define a `TimeSpan`? Are you sure it's not `DateTime.Parse(starttime.SelectedItem.Text).Time` you're looking for? – GigiSan Apr 12 '16 at 15:40
  • i have edited my code according to ur suggestion but it gave exception of '*String was not recognized as a valid DateTime' edited my post u can check it out @GigiSan – ahmed Apr 12 '16 at 16:05
  • If you didn't solve the problem yet, try [this answer](http://stackoverflow.com/a/7616347/2898163) – GigiSan Apr 14 '16 at 09:53

1 Answers1

1

"11:00 AM" cannot be parsed with the TimeSpan.Parse function. You could use the ParseExact function as follows:

DateTime.ParseExact(starttime.SelectedItem.Text, "hh:mm tt", CultureInfo.InvariantCulture);

You can extract the time from the Parsed datetime with the ".TimeOfDay" function. That will give you the proper value and type

MarkB
  • 486
  • 3
  • 8
  • i should store ur above given line in variable of type DateTime? and field in database should also also be changed from time(7) to DateTime ? Right? – ahmed Apr 12 '16 at 15:45
  • You can extract the time from the Parsed datetime with the ".TimeOfDay" function. That will give you the proper value and type – MarkB Apr 12 '16 at 15:51
  • I tried ur suggestion but it gave exception:**String was not recognized as a valid DateTime** and edited my code also.. u can check if i did it correctly. – ahmed Apr 12 '16 at 16:03
  • Then it's time to check the value of "starttime.SelectedItem.Text". It should of course not be "--Select--". Then it will not work of course – MarkB Apr 12 '16 at 16:08