2011-07-08 108 views
0

我遇到搜索表單有問題。我使用日期時間選擇器爲用戶提供他們喜歡的日期。當我嘗試設置任何日期時,它不會產生任何結果。貝婁是我的代碼:VB.NET中的日期時間搜索顯示沒有結果

Try 
    myDataSet.Clear() 
    myCommand = New SqlCommand("SELECT * FROM tblVisitor WHERE EnterDate LIKE @EnterDate", myConnection) 
    myCommand.Parameters.AddWithValue("@EnterDate", DateTime.Parse(cboEnterDate.Text)) 
    myAdapter = New SqlDataAdapter(myCommand) 
    myAdapter.Fill(myDataSet, "tblVisitor") 
    dgvVisitor.DataSource = myDataSet.Tables(0) 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 

而當我拿起一個日期從日期時間選擇器,它會顯示空白數據網格視圖身邊什麼都沒有,甚至在該日期可在數據庫中。

請幫我解決這個問題。

+0

我相信你有兩個問題:1等被用於對抗模式匹配字符串所以我不知道它的工作原理與日期列。 2.我不相信你可以用這種方式在LIKE子句中使用參數。 –

+0

您的代碼看起來像是實際使用組合框來選擇日期,而不是日期時間選擇器(它沒有Text屬性)。 – MartW

+0

tblVisitor中的輸入日期是什麼數據類型? – MartW

回答

1

日期不是字符串。你不應該使用LIKE操作符。通常,您會在搜索日期時使用BETWEEN運算符。

例子:

Try 
    myDataSet.Clear() 
    myCommand = New SqlCommand("SELECT * FROM tblVisitor WHERE EnterDate BETWEEN @EnterDate AND DATEADD(dd, 1, @EnterDate)", myConnection) 
    myCommand.Parameters.AddWithValue("@EnterDate", DateTime.Parse(cboEnterDate.Text)) 
    myAdapter = New SqlDataAdapter(myCommand) 
    myAdapter.Fill(myDataSet, "tblVisitor") 
    dgvVisitor.DataSource = myDataSet.Tables(0) 
Catch ex As Exception 
    MsgBox(ex.Message) 
End Try 
+0

但我希望用戶搜索特定的日期。我應該怎麼做? –

+1

假設日期只是日期(沒有時間),只需爲第二個參數加1,您將獲得該日期的所有記錄。 – Brian

+1

如果你真的對於確切的午夜的EnterDate降落偏執狂,將BETWEEN子句的結尾改爲:dateadd(s,-1,dateadd(dd,1,@EnterDate)) – Bill