[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

VB.NET INSERT ERROR - Conversion failed when converting datetime from character string

Posted on 2009-05-11
8
Medium Priority
?
308 Views
Last Modified: 2012-05-06
I am having issue with inserting some value from a textbox into SQL database from a windows form application.  Basically I have 2 textboxes that are use for Start/End Time.  So 6:00 or 14:00 will be the input data.  When I try to insert that, I get the following error.  Any ideas on what I need to do to these textboxes?

"Conversion failed when converting datetime from character string."

Below is my query:

CMD.COMMANDTEXT = "INSERT INTO EMP_TIME VALUES(" & strID & ", " & _
                                     "'" & txtStart.Text & "', '" & txtEnd.Text & "')"

Open in new window

0
Comment
Question by:holemania
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 15

Expert Comment

by:mohan_sekar
ID: 24358378
assuming you've a valid date value in the text field, use CDate(txtStart.Text)
0
 
LVL 8

Expert Comment

by:Bob Hoffman
ID: 24358415
Just the time value won't cast to a date. You have two choices:
1. Change your date fields in the Db to varchars
2. Load you time value as follows '1900-01-01' 06:00:00.000'
 
0
 

Author Comment

by:holemania
ID: 24359068
Yes it is just the time alone.  Is there anyway I can check to make sure it's in time format or way of automatically formatting it into time?  If that can be done, then I can also change the date field into varchars?

Example if someone enter 6:00 or 600 should be formated as 6:00?  If someone put in 123ABC, it would error out or give message that it needs to be in time format?
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 8

Accepted Solution

by:
Bob Hoffman earned 1600 total points
ID: 24359307
If your using your time values later in your SQL to test against ie(Start less the End, etc) I would leave them as date fields. You could use the IsTime function I supplied to check for a valid time. If your just storing the time to display ot print later store it as varchar(5) and use the TimeMask sub and the KeyPress and LostFocus events to make sure the time is valid.
   Private Function IsTime(ByVal strTime As String) As Boolean
        Try
            If IsDate("1900-01-01 " & strTime.Trim()) Then Return True
            Return False
        Catch ex As Exception
            Return False
        End Try
 
    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Call TimeMask(TextBox1.Text, Asc(e.KeyChar))
    End Sub
 
    Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus
        'Edit date
        If Trim$(TextBox1.Text) <> "" Then
            If Not IsDate(TextBox1.Text) Then
                MsgBox("Time is invalid.", vbOKOnly, "Error message")
                TextBox1.Focus()
            Else
                TextBox1.Text = Format(TextBox1.Text, "hh:mm")
            End If
        End If
    End Sub
 
    Public Sub TimeMask(ByVal strTime As String, ByVal KeyAscii As Integer)
 
        'Allow these keys
        If (KeyAscii = System.Windows.Forms.Keys.Back) _
         Or KeyAscii = System.Windows.Forms.Keys.Space _
         Or KeyAscii = System.Windows.Forms.Keys.Left _
         Or KeyAscii = System.Windows.Forms.Keys.Right _
         Or KeyAscii = System.Windows.Forms.Keys.Delete Then
            Exit Sub
        End If
 
        'Only Allow ":" in positions 3
        If KeyAscii = 58 Then
            If Len(strTime) <> 2 Then
                KeyAscii = 0
                Exit Sub
            End If
        End If
 
        'Only allow numbers and  ":"
        If (KeyAscii < 48 Or KeyAscii > 58) Then
            KeyAscii = 0
            Exit Sub
        End If
 
        ' Send ":"
        If Len(strTime) = 1 Then
            System.Windows.Forms.SendKeys.Send(":")
        End If
 
    End Sub

Open in new window

0
 
LVL 8

Expert Comment

by:Bob Hoffman
ID: 24359336
use this lostfocus handle not the one above.
    Private Sub TextBox1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.LostFocus
        'Edit date
        If Trim$(TextBox1.Text) <> "" Then
            If Not IsDate(TextBox1.Text) Then
                MsgBox("Time is invalid.", vbOKOnly, "Error message")
                TextBox1.Focus()
            Else
                TextBox1.Text = Format(CDate(TextBox1.Text), "HH:mm")
            End If
        End If
    End Sub

Open in new window

0
 
LVL 15

Expert Comment

by:JackOfPH
ID: 24360497
My Suggestion to you.

1) Change the datatype of the field in your database to DateTime.
2) Then in storing the value, use the function I posted below to check if you have a valid time before saving it.
Private Function IsValidTime(ByVal Time As String) As Boolean
        Return DateTime.TryParse(Time, New DateTime)
End Function

Open in new window

0
 
LVL 15

Assisted Solution

by:JackOfPH
JackOfPH earned 400 total points
ID: 24360500
And here is an example on how you can use it.

Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
        If IsValidTime(Me.TextBox1.Text) = False Then
            MessageBox.Show("Invalid time entered.")
            e.Cancel = True
        End If
End Sub

Open in new window

0
 

Author Closing Comment

by:holemania
ID: 31580301
Thanks.  That worked well.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses
Course of the Month19 days, 23 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question