Question Convert String to SQL Date

bradja

New member
Joined
Oct 17, 2011
Messages
3
Programming Experience
Beginner
Hi All,

I am new to the forums and am wondering if anyone is able to help me with something that I have been struggling to get my head around for ages.

I am using Visual Studio 2010 VB and I have a text box where a user can enter a date eg. 10/10/2010

I need to convert this string into a date that I can pass into a date column in Microsoft SQL Server 2008.

Is anyone able to show me some code example or point me in the right direction?


Cheers!
 
I have done a bit of messing around and I have come up with this..
User enters 10/10/2010 into a Text Box (DateArrivedActualTxtBox), then clicks on a button (Button1).
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLDate As Date
Dim OrdNumber As Integer = Val(OrderNumberActualLbl.Text)
Dim DateArrivedSQLReplace = DateArrivedActualTxtBox.Text.Replace("\", "")
SQLDate = Convert.ToDateTime(DateArrivedActualTxtBox.Text)
myConn.Open()
Dim cmdText As String = "UPDATE StoreOrders SET DateArrived= @SQLDate WHERE OrderNumber= '" & OrdNumber & "'"
Dim cmd As SqlCommand = New SqlCommand(cmdText, myConn)
With cmd.Parameters.Add(New SqlParameter("@SQLDate", SQLDate))
End With
cmd.ExecuteNonQuery()
myConn.Close()
myConn = Nothing

To me it feels like a really sloppy way of getting it to do what I want, does anyone have any helpful suggestions as to any ways of doing it better?
 
You can't really use Convert.ToDateTime unless you know for sure that the value will convert. If you're relying on user input then you don't know that because they could enter absolutely anything, or nothing. As such, you would really need to use Date.TryParse.

That said, why use a TextBox at all when you can use a DateTimePicker? It will handle the validation and conversion for you and then you simply get its Value property, which is a DateTime. If you want to zero the time then you simply get the Date property of that.
 
DateTimePicker sounds like an excellent idea. I've never used it before but I will look into it now.
Thanks for the help!
 
Back
Top