Question

I'm getting the following error message on my webform:

Cast from string "" to type 'Date' is not valid.

I'm assuming it's because of this line (but my assumption could be incorrect):

command.Parameters.Add(New SqlParameter("col3", SqlDbType.DateTime, 8)).Value = some_date_parameter

Which is in a function:

Function ProcessAction(ByVal col1 As Integer, ByVal col2 As String, ByVal col3 As Date, ByVal col4 As Integer, ByVal col5 As String) as something

    '...
    command.Parameters.Add(New SqlParameter("@col1", SqlDbType.Int, 4)).Value = col1
    command.Parameters.Add(New SqlParameter("@col2", SqlDbType.VarChar, 255)).Value = col2
    command.Parameters.Add(New SqlParameter("@col3", SqlDbType.DateTime, 8)).Value = col3
    command.Parameters.Add(New SqlParameter("@col4", SqlDbType.Int, 4)).Value = col4
    command.Parameters.Add(New SqlParameter("@col5", SqlDbType.VarChar, 255)).Value = col5

    '...

    Return something

End Function

Which is called via a button:

Sub ButtonClick(ByVal Source As Object, ByVal E As EventArgs)

    '...

    structRecord = ProcessAction(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text)

    '...

End Sub

Where structRecord is:

Public Structure structRecord
    Public col1 As Integer
    Public col2 As String
    Public col3 As Date
    Public col4 As Integer
    Public col5 As String
End Structure

The actual error gets shown on this line at runtime which is in the ButtonClick:

structRecord = ProcessAction(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text)

How can this problem be corrected? I basically want to allow the user to continue with the rest of the webapp, even if TextBox3.Text is left empty.

Was it helpful?

Solution

Typically, you'll test your inputs to ensure they are within a valid or acceptable range.

In the case of a date you'll want to verify that the value will convert to a date and if so, pass that as a parameter. If it's not a valid date then you can pass a null value to the query.

The query should be smart enough to accept a date or null; however, without that query I can't help you.

OTHER TIPS

You might try using the dateTime.TryParse method to validate the string that your passing in is a valid date/time value.

http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top