您好,我想知道是否有人能够帮助我解决我遇到的编码问题。
我有一个表单,用户可以在文本框中输入姓氏,以返回姓氏匹配的数据库(访问2013)的结果。这工作正常,如果文本框留空,我还希望查询返回数据库中的所有条目。这是我遇到问题的部分,当文本框留空时,不会返回任何结果。我已经在这个网站上搜索了几个问题,从目前为止我看到的代码应该可行。有人可以告诉我我的代码不正确吗?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'creates a list of all employees as per the search parameters
Dim dt As New DataTable
Dim query As String = " select [employeeid] as empolyeeid, (firstname &' '& lastname &' '& dob) as empdetails from employee where ((@lastname is null) or (lastname = @lastname))"
Using connection As New OleDbConnection(My Database Connection)
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
command.Parameters.AddWithValue("@lastname", txt_lastname.Text)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
If dt.Rows.Count > 0 Then
lb_search.DataSource = dt
lb_search.DisplayMember = "employeeid"
lb_search.ValueMember = "empdetails"
End If
End Sub
感谢阅读。非常感谢任何关于为什么这不起作用的见解感谢
答案 0 :(得分:1)
你应该替换
((@lastname is null) or (lastname = @lastname))
使用
((@lastname = '') or (lastname = @lastname))
您的文本框可以包含空字符串,但不能为空。
安全使用txt_lastname.Text.Trim
答案 1 :(得分:1)
问题是TextBox.Text属性永远不会为null
当你将TextBox留空时,你有Text=String.Empty
,而不是空。
当然解决方法是检查空字符串而不是空
Dim query As String = "select [employeeid] as empolyeeid, " & _
"(firstname &' '& lastname &' '& dob) as empdetails " & _
"from employee where ((@lastname = '') or " & _
"(lastname = @lastname))"
但您也可以简化命令文本并将VB代码更改为
Dim query As String = "select [employeeid] as empolyeeid, " & _
"(firstname &' '& lastname &' '& dob) as empdetails " & _
"from employee where lastname LIKE @lastname"
command.Parameters.AddWithValue("@lastname",
if(string.IsNullOrWhiteSpace(txt_lastname.Text),
"%", txt_Lastname.Text.Trim())
这样,WHERE子句上只有一个条件,匹配是使用LIKE运算符完成的。这样,如果你的文本框是空白的,你可以传递匹配任何%
的通配符lastname
,而如果有效的姓氏,你也可以匹配lastname字段,如果输入了值的话使用不同的情况(下/上不匹配)