Haminteu
Haminteu

Reputation: 1334

Time Datatype SQL Server 2008 and C#


I have one textbox (asp:textbox). I am using C#.NET and SQL Server 2008 R2 as the database. I've a problem when I'm trying to input the time. I.e. 08:00, 14:00, etc.
After I clicked Submit, it should be store to the table. But error. The error is "String was not recognized as a valid TimeSpan". The fieldname is 'YourTime', datatype time(7).

I am using sqlcommand to store it to the table.

cmd.Parameters.Add("@YourTime", SqlDbType.Time, 7).Value = txtYourTime.Text;

Anyone can help for this?
Thank you so much.


Cheers,

Upvotes: 0

Views: 169

Answers (2)

Richard
Richard

Reputation: 108975

Best approach is to convert the text (string) value from txtYourTime.Text into a TimeSpan using TimeSpan.TryParse.

Pass the CultureInfo (for the IFormatProvider parameter) that reflect's your user (different cultures use different formats). This ensures you control these parameters rather than defaults which reflect the setup of the servers rather than the user's intent.

EDIT: Sample as requested:

var ci = CultureInfo.GetCultureInfo(Request.UserLanguages[0]);
TimeSpan ts;
if (TimeSpan.TryParse(txtYourTime.Text, ci, out ts)) {
  cmd.Parameters.Add("@YourTime", SqlDbType.Time).Value = ts;
} else {
  // Report invalid input to user.
}

Upvotes: 1

user2579857
user2579857

Reputation:

You should convert your string into a valid TimeSpan like this:

myTime = TimeSpan.Parse(txtYourTime.Text);
cmd.Parameters.Add("@YourTime", SqlDbType.Time, 7).Value = myTime;

Upvotes: 0

Related Questions