Ok, this is a common setup.
You might have say 2-10 optional critera. If you leave them blank, you ignore. However, if you type in City, and then say a Name or whatever?
You don't want or - you want BOTH critera to be applied. In fact, this is the default setup I have for the vast majority of my search forms.
So, blank (no value) = ignore this criteria.
So, enter a value, then we apply that criteria - and all values must match ("and").
So, there are a number of ways to do this, but ultimately?
We should over time allow adding of more criteria. In other words, if we have 2 or 15 options, the code should not really care.
So, I suggest this pattern:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strSQL As String = "SELECT * FROM tblHotels "
Dim strWhere As String = ""
Dim cmdSQL As New SqlCommand(strSQL)
' hotel
If txtHotel.Text <> "" Then
strWhere = "(HotelName = *anonymous user*)"
cmdSQL.Parameters.Add("*anonymous user*", SqlDbType.NVarChar).Value = txtHotel.Text
End If
' city
If txtCity.Text <> "" Then
If strWhere <> "" Then strWhere &= " AND "
strWhere &= "(City = @City)"
cmdSQL.Parameters.Add("@City", SqlDbType.NVarChar).Value = txtCity.Text
End If
' is hotel active
If chkHotelActive.Checked Then
If strWhere <> "" Then strWhere &= " AND "
strWhere &= "(Active = @Active)"
cmdSQL.Parameters.Add("@Active", SqlDbType.Bit).Value = 1
End If
' state
If txtState.Text <> "" Then
If strWhere <> "" Then strWhere &= " AND "
strWhere &= "(State = @State)"
cmdSQL.Parameters.Add("@State", SqlDbType.NVarChar).Value = txtState.Text
End If
If strWhere <> "" Then
cmdSQL.CommandText = strSQL & " WHERE " & strWhere
End If
' OPTIONAL order by
cmdSQL.CommandText &= " ORDER BY HotelName"
Dim rstData As New DataTable
Using conn As New SqlConnection(My.Settings.Test4)
Using cmdSQL
cmdSQL.Connection = conn
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
End Using
End Using
' at this point, do whateever with the results
DataGridView1.DataSource = rstData
So, note close - we can add 2 or 50 options. We STILL get to use strong typed parameters (no sql injection), and we simple build up as we go along, and we simple skip any control that has no value.
And if later on, you want to add 5 more controls, combo or whatever to this search page, then you can scroll down to the last value, and just start cookie cutting the additonal criteria to the end of this.
Now, I used full 100% match, but, we could just as well assume trailing wild card, and thus the criteria would look like:
' hotel
If txtHotel.Text <> "" Then
strWhere = "(HotelName like *anonymous user* + '%')"
cmdSQL.Parameters.Add("*anonymous user*", SqlDbType.NVarChar).Value = txtHotel.Text
End If
Regards,
Albert D. Kallal (Access MVP 2003-2017)
Edmonton, Alberta Canada