2013-03-18 46 views
0

我让我的网页表单以下错误消息的错误:空TextBox1.Text是给我

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

我猜想这是因为该行的(但我的假设可能是不正确的):

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

这是一个功能:

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 

这是通过一个按钮叫:

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

    '... 

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

    '... 

End Sub 

其中structRecord是:

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 

实际的错误被显示在这条线在运行时是在ButtonClick

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

如何这个问题得到纠正?我基本上希望允许用户继续使用其余的webapp,即使TextBox3.Text保留为空。

回答

0

通常,您将测试您的输入以确保它们处于有效或可接受的范围内。

在日期的情况下,您需要验证该值是否会转换为日期,如果是,请将其作为参数传递。如果它不是一个有效的日期,那么你可以传递一个空值给查询。

该查询应该足够聪明以接受日期或null;然而,如果没有这个问题,我不能帮你。

+0

所以你认为被触发,因为查询的错误,而不是'Struct'这是预期的,而不是一个'String'为'col3'一个'Date'? – oshirowanen 2013-03-18 16:31:57

+0

@oshirowanen:不,我建议你需要做两件事中的一件。或者更改ProcessAction以接受所有字符串,并在其内部进行验证,或者在调用ProcessAction之前执行正确的验证和转换。无论哪种方式,当您知道它会失败时,您需要测试并执行转换,而不是依赖于隐式转换。 – NotMe 2013-03-18 16:33:53

相关问题