我正在Visual Studio 2012中构建一个搜索页面,而不是为每个参数使用单独的工具条,而是使用与用户输入一样多的参数。使用两个日期时间参数并允许它们为空时会出现问题。我已经从How to pass a Null date variable to SQL Server database和Dealing with DateTime and Null values获得了很好的指导,因此我认为使用 Dbnull.value 的方式是可行的,但是,我不明白代码在哪里在我的页面上。这是按钮sub和相应的查询代码:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.Claims_IncidentsTableAdapter.FillByAllOptions(Me.IncidentSearchDataSet.Claims_Incidents, LastNameTextBox.Text, ClaimNumberTextBox.Text, InsuredNameTextBox.Text, FirstNameTextBox.Text,
New System.Nullable(Of Date)(CType(DOLTextBox.Text, Date)), New System.Nullable(Of Date)(CType(DRTextBox.Text, Date)), AssertedCheckBox.CheckState, CWSCheckBox.CheckState)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
End Sub
查询
SELECT Claim_Number, Insured_Name, Policy_Number, lastname, firstname, dateofloss, datereceived, asserted, movedtocws
FROM dbo.Claims_Incidents
WHERE (@lastname IS NULL OR
lastname LIKE '%' + @lastname + '%') AND (@Claim_Number IS NULL OR
Claim_Number LIKE '%' + @Claim_Number + '%') AND (@Insured_Name IS NULL OR
Insured_Name LIKE @Insured_Name + '%') AND (@firstname IS NULL OR
firstname LIKE '%' + @firstname + '%') AND (@dateofloss IS NULL OR
dateofloss = @dateofloss) AND (@datereceived IS NULL OR
datereceived = @datereceived) AND (@asserted IS NULL OR
asserted = 1) AND (@movedtocws IS NULL OR
movedtocws = 1)
目前,我收到错误消息“从字符串转换”“到'类型'日期'无效。”如果我将日期字段留空。我明白了,但是我把代码放在哪里?如果要进入函数,我在哪里放功能代码?我不明白它的适当位置。
答案 0 :(得分:1)
<强>原因强>
以下是您的问题:
New System.Nullable(Of Date)(CType(TEXTBOX.Text, Date))
如果TEXTBOX
为空(""
),则无法将其转换为日期。事实上,System.Nullable(Of Date)
永远不会为空,因为空TEXTBOX
的值为String.Empty
,而不是Nothing
。
解决方案
替换为:
If(String.IsNullOrEmpty(TEXTBOX.Text), New Nullable(Of Date), New Nullable(Of Date)(Date.Parse(TEXTBOX.Text)))