Click here to Skip to main content
15,894,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have a form with four list boxes .AUTHORS ,PUBLISHERS,YEARPUBLISHED and GENRE.

At present the code works fine providing I tick an item in all of the four boxes.What I wanted to be able to do is click on less than the four and get a result.For example if I just wanted the details of one author ,I would just like to tick on the name in the authors box get those details up and be able to ignore the remainder of the boxes.
I have tried fiddling about with the code but just can't seem to crack it .Any help greatly appreciated

VB
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim con As New OleDb.OleDbConnection

        Dim dbProvider As String
        Dim dbSource As String

        Dim ds As New DataSet

        Dim tables As DataTableCollection = ds.Tables

        Dim source1 As New BindingSource()

        Dim da As New OleDb.OleDbDataAdapter

        Dim sql As String



        Dim aa As String = authorList.Text

        Dim bb As String = publisherList.Text

        Dim cc As String = yearpublishedList.Text

        Dim dd As String = genreList.Text



        dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"

        dbSource = "Data Source = C:\Documents and Settings\Administrator\Desktop\Authors.accdb"

        con.ConnectionString = dbProvider & dbSource

        con.Open()

       

        sql = "SELECT * FROM books WHERE author = '" & aa & "' AND publisher = '" & bb & "' AND yearpublished = '" & cc & "' AND genre = '" & dd & "' "


       
        

        da = New OleDb.OleDbDataAdapter(sql, con)

        da.Fill(ds, "Authors")
        

        Dim view1 As New DataView(tables(0))

        source1.DataSource = view1

        DataGridView1.DataSource = view1

        DataGridView1.Refresh()











        con.Close()



    End Sub
Posted
Comments
[no name] 13-May-14 6:54am    
You should probably research how to write an IF statement and use a stringbuilder.

As suggest by Wes Aday, you need to build up your SQL string bit by bit. The most efficient way of doing this is to use a StringBuilder for which you will need
Imports System.Text
Whilst building up your string you will need to know if the "AND"s are required in the string so you will need a Boolean or an integer to keep track of how many filters you have already applied.
You should also use Parameterized queries[^] to help prevent sql injection - never build a sql query by concatenating strings that can be entered by a user!

Something like this should work
VB
'Initialise a string builder with the first part of the query
Dim sql As StringBuilder = New StringBuilder("SELECT * FROM books WHERE ")
'This Boolean will be set to True if we have added a filter already
Dim AndRequired As Boolean = False
'We will be adding parameters to this Command
Dim cmd As OleDbCommand = New OleDbCommand()

cmd.Connection = con

'Do we have anything in aa (authorList.Text)
If aa.Length > 0 Then
    'Add the filter to the SQL
    sql.Append("author = ?")
    
    'Add the value into the parameter list
    cmd.Parameters.Add("@author", OleDbType.VarChar, 30).Value = aa     
    'Change the numbers in the parameter to the sizes of your columns
    
    'Flag that we have already added a filter
    AndRequired = True
End If

'Next check ...
If bb.Length > 0 Then
    'If we have already added a filter then we need the " AND "
    If AndRequired Then sql.Append(" AND ")
    'The rest is the same as for aa
    sql.Append("publisher = ?")
    cmd.Parameters.Add("@publisher", OleDbType.VarChar, 30).Value = bb
    AndRequired = True
End If
If cc.Length > 0 Then
    If AndRequired Then sql.Append(" AND ")
    sql.Append("yearpublished = ?")
    cmd.Parameters.Add("@yearpublished", OleDbType.VarChar, 4).Value = cc
    AndRequired = True
End If
If dd.Length > 0 Then
    If AndRequired Then sql.Append(" AND ")
    sql.Append("genre = ?")
    cmd.Parameters.Add("@genre", OleDbType.VarChar, 30).Value = dd
    AndRequired = True  'Not strictly necessary but you might want to add more stuff later so put it in anyway
End If

'Let the Command know the sql we've constructed - note the .ToString IS required
cmd.CommandText = sql.ToString()
da = New OleDbDataAdapter()
da.SelectCommand = cmd
da.Fill(ds, "Authors")
 
Share this answer
 
Hi Chill,

Many many thanks for your detailed reply.I can see the logic in your code but after several hours of attempting to re-arrange my code around your code I keep coming up with the following errors.

Error 1 Type 'OleDbType' is not defined.
Error 2 Local variable 'sql' is already declared in the current block.
Error 3 Type 'OleDbCommand' is not defined.
Error 8 Type 'OleDbDataAdapter' is not defined.

Here is the latest attempt at the code,I am not too sure if I should include my old sql string,but the times I have I get even more errors any hints much appreciated.
VB
Imports System.Text


Public Class Form1


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim con As New OleDb.OleDbConnection

        Dim dbProvider As String
        Dim dbSource As String

        Dim ds As New DataSet

        Dim tables As DataTableCollection = ds.Tables

        Dim source1 As New BindingSource()

        Dim da As New OleDb.OleDbDataAdapter
        Dim tt As New OleDbType
        Dim sql As String



        Dim aa As String = authorList.Text

        Dim bb As String = publisherList.Text

        Dim cc As String = yearpublishedList.Text

        Dim dd As String = genreList.Text
        'Initialise a string builder with the first part of the query
        Dim sql As StringBuilder = New StringBuilder("SELECT * FROM books WHERE ")
        'This Boolean will be set to True if we have added a filter already
        Dim AndRequired As Boolean = False
        'We will be adding parameters to this Command
        Dim cmd As OleDbCommand = New OleDbCommand()

        cmd.Connection = con

        'Do we have anything in aa (authorList.Text)
        If aa.Length > 0 Then
            'Add the filter to the SQL
            sql.Append("author = ?")

            'Add the value into the parameter list
            cmd.Parameters.Add("@author", OleDbType.VarChar, 30).Value = aa
            'Change the numbers in the parameter to the sizes of your columns

            'Flag that we have already added a filter
            AndRequired = True
        End If

        'Next check ...
        If bb.Length > 0 Then
            'If we have already added a filter then we need the " AND "
            If AndRequired Then sql.Append(" AND ")
            'The rest is the same as for aa
            sql.Append("publisher = ?")
            cmd.Parameters.Add("@publisher", OleDbType.VarChar, 30).Value = bb
            AndRequired = True
        End If
        If cc.Length > 0 Then
            If AndRequired Then sql.Append(" AND ")
            sql.Append("yearpublished = ?")
            cmd.Parameters.Add("@yearpublished", OleDbType.VarChar, 4).Value = cc
            AndRequired = True
        End If
        If dd.Length > 0 Then
            If AndRequired Then sql.Append(" AND ")
            sql.Append("genre = ?")
            cmd.Parameters.Add("@genre", OleDbType.VarChar, 30).Value = dd
            AndRequired = True  'Not strictly necessary but you might want to add more stuff later so put it in anyway
        End If

        'Let the Command know the sql we've constructed - note the .ToString IS required
        cmd.CommandText = sql.ToString()
        da = New OleDbDataAdapter()
        da.SelectCommand = cmd
        da.Fill(ds, "Authors")


        dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"

        dbSource = "Data Source = C:\Documents and Settings\Administrator\Desktop\Authors.accdb"

        con.ConnectionString = dbProvider & dbSource

        con.Open()



        'sql = "SELECT * FROM books WHERE author = '" & aa & "' AND publisher = '" & bb & "' AND yearpublished = '" & cc & "' AND genre = '" & dd & "' "





        da = New OleDb.OleDbDataAdapter(sql, con)

        da.Fill(ds, "Authors")


        Dim view1 As New DataView(tables(0))

        source1.DataSource = view1

        DataGridView1.DataSource = view1

        DataGridView1.Refresh()











        con.Close()



    End Sub

End Class
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900