You need to add a space between your search statements:
If R1.Checked Then sql = sql & " where datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " [centr] ='" & Me.centra.Text & "' "
If R3.Checked Then sql = sql & " and [Priorité] ='" & Me.Priorite.Text & "' "
If R4.Checked Then sql = sql & " and [Etat_intervention] ='" & Me.etat.Text & "' "
Your SQL reads like this: where datevisite like '%%'and [Priorité] =''and
Better Solution:
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn.Open()
Dim sql = "SELECT * FROM [maint] where 1=1 "
dt.Clear()
If R1.Checked Then sql = sql & " and datevisite like '%" & dateintervention.Text & "%' "
If R2.Checked Then sql = sql & " and [centr] ='" & Me.centra.Text & "'"
If R3.Checked Then sql = sql & " and [Priorité] ='" & Me.Priorite.Text & "'"
If R4.Checked Then sql = sql & " and [Etat_intervention] ='" & Me.etat.Text & "'"
Dim adapter As New OleDbDataAdapter(sql, MyConn)
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
MyConn.Close()
End Sub
With Parameters:
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim adapter As New OleDbDataAdapter()
Dim command As New OleDbCommand()
Dim sql = "SELECT * FROM [maint] where 1=1 "
Try
MyConn.Open()
dt.Clear()
If R1.Checked Then
sql = sql & " and datevisite like '' "
command.Parameters.AddWithValue("datevisite", "%" & dateintervention.Text & "%")
End If
If R2.Checked Then
sql = sql & " and [centr] = ? "
command.Parameters.AddWithValue("centr", Me.centra.Text)
End If
If R3.Checked Then
sql = sql & " and [Priorité] = ? "
command.Parameters.AddWithValue("Priorité", Me.Priorite.Text)
End If
If R4.Checked Then
sql = sql & " and [Etat_intervention] = ? "
command.Parameters.AddWithValue("Etat_intervention", Me.etat.Text)
End If
command.Connection = MyConn
command.CommandText = sql
adapter.SelectCommand = command
adapter.Fill(dt)
DGV.DataSource = dt
DGV.Refresh()
Catch exp As Exception
Throw exp
Finally
If MyConn IsNot Nothing Then MyConn.Close()
End Try
End Sub
如果R1.Checked为false且R2.Checked为true,那么您没有WHERE关键字......您没有正确构建动态SQL语句。
此外,它非常容易受到SQL注入
的影响