vb中的datagrid控件问题

来源:百度知道 编辑:UC知道 时间:2024/05/30 19:06:17
Private Sub Command2_Click() '精确查询信息

Dim strSQL As String
Dim intNum As Integer
strSQL = "select * from zhaijidi where "
If Trim(Text1.Text) <> "" Then strSQL = strSQL & "户主姓名='" & Trim(Text1.Text) & "'"
If Trim(Text2.Text) <> "" Then strSQL = strSQL & "and 房屋编号='" & Trim(Text2.Text) & "'"
If Trim(Text3.Text) <> "" Then strSQL = strSQL & "and 建筑时间='" & Trim(Text3.Text) & "'"
If Trim(Text4.Text) <> "" Then strSQL = strSQL & "and 地籍号='" & Trim(Text4.Text) & "'"

If Mid(strSQL, 27, 1) = "a" Then
strSQL = Left(strSQL, 26) & Mid(strSQL, 30)
End If

If Mid(strSQL, 28, 1) = "" Then
MsgBox "未输入查询项目,将查询出所有信息", , "提示"

你这样写如果Text1.Text为空("")的话,会导致条件变成
where and ....或者所有TextBox都为空的话,就会变成 where and ,这样当然错误啦

把If Trim(Text1.Text) <> "" Then strSQL = strSQL & "户主姓名='" & Trim(Text1.Text) & "'" 换成这样

If Trim(Text1.Text) <> "" Then
strSQL = strSQL & "户主姓名='" & Trim(Text1.Text) & "' "
else
'总之,第一个出现的条件一定这样操作,保证where后面总有一个条件
strSQL = strSQL & "1=1 " '这样可以保证where后面总有一个条件
end if

还有可能就是你每个条件之间没加空格,可以每个条件后面加一个空格,或者每个条件的最前面加空格
If Trim(Text1.Text) <> "" Then strSQL = strSQL & " 户主姓名='" & Trim(Text1.Text) & "'" else strSQL = strSQL & "1=1 "
If Trim(Text2.Text) <> "" Then strSQL = strSQL & " and 房屋编号='" & Trim(Text2.Text) & "'"
If Trim(Text3.Text) <> "" Then strSQL = strSQL & " and 建筑时间='&