Select Access Items where Checkboxes indicate Field Values - ms-access

In my database I have a table with several yes/no columns.
Now, I have a unbound form with some unbound checkboxes and a listbox bound to a special query just for it.
I want to use the checkboxes on the form to filter the listbox and display items in the list that have matching values.
For example,
If I check box1 on the form, any item that contains field1 in the listbox should show.
If I check box2 and box3 on the form, any item that contains field2 AND field3 should display in the listbox. If an item does not have both field3 AND field3, their entries should not show in the list because the boxes are not checked.
Each control on the form uses an on-click event procedure to cause the list to requery.
Right now, this doesn't work right for me. My listbox only displays items when ALL the values match the checkbox. So, if I check box1 and box2, I only get the results from items that have only field1 and field2. If the item also has field3, it doesn't display - and this is my problem.
This is what my query looks like so far:
SELECT MyQuery.title, field1, MyQuery.field2, MyQuery.field3
FROM MyQuery
WHERE (
(
(MyQuery.field1) like [Forms]![Ability Finder]![box1]
)AND(
(MyQuery.field2) like [Forms]![Ability Finder]![box2]
)AND(
(MyQuery.field2) like [Forms]![Ability Finder]![box3]
)
);
Maybe I'm going about this all the wrong way. Also, I have about 20 checkboxes for which I need to do this.
SELECT MyQuery.cat, MyQuery.nickname, MyQuery.title, MyQuery.level, MyQuery.field1, MyQuery.field2, MyQuery.field3
FROM MyQuery
WHERE (
((MyQuery.field1)=[Forms]![Ability Finder]![box1] Or [Forms]![Ability Finder]![box1] Is Null)
AND ((MyQuery.field2)=[Forms]![Ability Finder]![box2] Or [Forms]![Ability Finder]![box2] Is Null)
AND ((MyQuery.field3)=[Forms]![Ability Finder]![box3] Or [Forms]![Ability Finder]![box3] Is Null)
);

Not sure if you want to take a crack at writing the event handling in VBA, but it will make this task a lot easier. You can construct the SQL query dynamically each time a checkbox is clicked, and it can handle any additional checkboxes if you add them down the line simply by adjusting the For loop. You call the Sql constructor function for the Click event of each checkbox, then set the listbox's row source in the constructor function.
Private Sub Check1_Click()
ConstructSqlQuery
End Sub
Private Sub Check2_Click()
ConstructSqlQuery
End Sub
Private Sub Check3_Click()
ConstructSqlQuery
End Sub
...
Private Sub ConstructSqlQuery()
Dim sql As String
Dim numChecked As Integer
Dim checkboxName As String
Dim criteriaBoxName As String
numChecked = 0
'the 1=1 is a dummy value that always returns true. It makes it easier to append additional "and" clauses.
sql = "select field1, field2, field3, ... from MyQuery where 1=1"
For x = 1 To 15
checkboxName = "Check" & x
criteriaBoxName = "Text" & x
If Me.Controls(checkboxName).Value = -1 Then
sql = sql & " and field" & x & " like '*" & Me.Controls(criteriaBoxName).Value & "*'"
numChecked = numChecked + 1
End If
Next
If numChecked = 0 Then
'if nothing is checked, don't show anything.
Me.List0.RowSource = ""
Else
Me.List0.RowSource = sql
End If
Me.List0.Requery
End Sub

Related

Access ComboBox binding and Selected Value

I am trying to create a simple form for entering data. I have two tables, jobs and reports. The report table refers to a job with a one to many (one job, many reports). When browsing through the reports I want the combo box that lists all of the jobs to show the corresponding job as the selected value. This is easy in a .NET environment, but I'm not understanding how to set this up in the property sheet for the combobox. My ComboBox record source is from a query:
SELECT Jobs.UID, Jobs.Projectcode, Jobs.Projectname, Jobs.Owner, Jobs.Contractor
FROM Jobs
ORDER BY Jobs.[Projectcode];
And the form is based on a query that joins the tables:
SELECT Report.ID, Report.ReportNumber, Report.ReportDate, Report.Temperature, Report.Weather, Report.Progress, Report.PeopleatOAC, Report.Trades, Jobs.UID, Jobs.Projectname, Jobs.Owner, Jobs.Contractor
FROM Report
INNER JOIN Jobs ON Jobs.UID = Report.JobID
UNION ALL SELECT Report.ID, Report.ReportNumber, Report.ReportDate,
Report.Temperature, Report.Weather, Report.Progress, Report.PeopleatOAC,
Report.Trades, Jobs.UID, Jobs.Projectname, Jobs.Owner, Jobs.Contractor
FROM Report
LEFT JOIN Jobs ON Jobs.UID = Report.JobID WHERE (((Report.JobID) Is Null))
ORDER BY Report.ID;
The way I have this set up, a report can have a null job field. So I want to be able to select a job from the combo box to update the report table AND I want the combo box to reflect the correct job if the current record has a jobID associated with it. Is this possible?
What I have implemented is a tie to the Current event for the form that sets the combobox value (or clears it) depending on the JobID. As well as an tied to the changed event for the combobox to update the database with a selection. This works well enough but VBA feels so limiting compared to C#, WPF, and MVVM.
For anyone stumbling accross this with a similar question here are the 2 VBA functions:
Private Sub Form_Current()
Dim JobID As Integer
Dim i As Integer
Dim TempVal As Variant
Dim TestVal As Integer
TempVal = Me.JobID.Value
If Me.JobID.Value <> Empty Then
JobID = Me.JobID.Value
Else: JobID = -2
End If
With Me.JobCodeCombo
If (JobID >= 0) Then
For i = 0 To .ListCount - 1
TestVal = .Column(0, i)
If .Column(0, i) = JobID Then
.Value = .ItemData(i)
Exit For
End If
Next
Else
Me.JobCodeCombo = Null
End If
End With
End Sub
Private Sub JobCodeCombo_Change()
Dim ReportID As Long
Dim JobID As Long
Dim dbs As DAO.Database
Dim qdfUpdateJobID As DAO.QueryDef
Dim CurrentRecord As Long
CurrentRecord = Me.CurrentRecord
Set dbs = CurrentDb
Set qdfUpdateJobID = dbs.QueryDefs("UpdateReportWithJobID")
ReportID = Me.ReportID.Value
JobID = Me.JobCodeCombo.Column(0)
qdfUpdateJobID.Parameters(0).Value = JobID
qdfUpdateJobID.Parameters(1).Value = ReportID
qdfUpdateJobID.Execute
qdfUpdateJobID.Close
DoCmd.Save acForm, "Form1"
Me.Requery
DoCmd.GoToRecord acDataForm, "Form1", acGoTo, CurrentRecord
End Sub
The query called from the second function is a simple update query in my access file that has two parameters:
PARAMETERS [P1] Long, [P2] Long;
UPDATE Report SET JobID = P1
WHERE [ID] = P2;

How to implement a more efficient search feature?

In my database there are 3 column which is Name, Age, Gender.
In the program, I only want to use 1 search button. When the button is clicked, the program determine which 3 of the textbox has input and search for the right data.
How do you work with the query? For example if Name and Gender has text, the query :
"Select * from table Where (Name = #name) AND (Gender = #gender)"
And when only name is entered, I only query for the name. Must I check textbox by textbox whether there is user input and then write multiple query for each of them? Or is there a better way to do this?
Edit (29/5/16) : I tried doing this another way like this
myCommand = New MySqlCommand("Select * from project_record Where
(FloatNo = #floatNo OR FloatNo = 'None') AND
(DevCompanyName = #devCompanyName OR DevCompanyName = 'None') AND
(DevType = #devType OR DevType = 'None') AND
(LotPt = #lotPt OR LotPt = 'None') AND
(Mukim = #mukim OR Mukim = 'None') AND
(Daerah = #daerah OR Daerah = 'None') AND
(Negeri = #negeri OR Negeri = 'None') AND
(TempReference = #tempRef OR TempReference = 'None')", sqlConn)
But as you can guess already it will not work efficiently as well because if I only enter input for DevType and leave other textboxes blank, the query will not pull up all the records for DevType only. It will just display as no records.
Select * from table
Where (Name = #name OR #name is Null)
AND (Gender = #gender OR #gender is Null)
...
it should be one query
Other answers have explained how to simplify the query. It is especially important to get rid of the ORs, since they inhibit any use of indexes.
Once you have the query build cleanly, you need to think about the dataset and decide which columns are usually used for filtering. Then make a few INDEXes for them. You won't be able to provide 'all' possible indexes, hence my admonition that you think about the dataset.
When building indexes, you can have single-column or multiple-column indexes. For your type of data, I would suggest starting with several 2-column indexes. Make sure each index starts with a different column.
For Where (Name = #name) AND (Gender = #gender), here are some notes:
INDEX(gender) is useless because of low 'cardinality';
INDEX(gender, name) might be useful, but the following would be better:
INDEX(name)
Things like name and DevCompanyName are virtually unique, so a 1-column index is probably good.
If you had gender and age, then INDEX(age, gender) might be useful.
MySQL will almost never use two indexes for a single SELECT.
By the way, the construction of the WHERE could be done in a Stored Procedure. You would need CONCAT, PREPARE, etc.
Original answer
(scroll down to see update)
Can you try the following:
build a list only including values of the textboxes that have an input
set a string of the join the items of that list together with the " AND " string
append that string to your standard SELECT statement
The code looks like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Predicate1 As String = Me.TextBox1.Text
Dim Predicate2 As String = Me.TextBox2.Text
Dim Predicate3 As String = Me.TextBox3.Text
Dim PredicateList As New List(Of String)
Dim WhereClause As String
Dim Query As String
If Predicate1 <> String.Empty Then
PredicateList.Add("Name=""" & Predicate1 & """")
End If
If Predicate2 <> String.Empty Then
PredicateList.Add("Age=""" & Predicate2 & """")
End If
If Predicate3 <> String.Empty Then
PredicateList.Add("Gender=""" & Predicate3 & """")
End If
WhereClause = String.Join(" AND ", PredicateList.ToArray)
Query = "SELECT * FROM TABLE WHERE " & WhereClause
MessageBox.Show(Query)
End Sub
Update
Further to the comments re SQL injection, here is an updated sample.
Dim Command As SqlClient.SqlCommand
Dim Predicate1 As String = Me.TextBox1.Text
Dim Predicate2 As String = Me.TextBox2.Text
Dim Predicate3 As String = Me.TextBox2.Text
Dim ParameterList As New List(Of SqlClient.SqlParameter)
Dim PredicateList As New List(Of String)
Dim BaseQuery As String = "SELECT * FROM TABLE WHERE "
If Predicate1 <> String.Empty Then
PredicateList.Add("name = #name")
ParameterList.Add(New SqlClient.SqlParameter("#name", Predicate1))
End If
If Predicate2 <> String.Empty Then
PredicateList.Add("age = #age")
ParameterList.Add(New SqlClient.SqlParameter("#age", Predicate2))
End If
If Predicate3 <> String.Empty Then
PredicateList.Add("gender = #gender")
ParameterList.Add(New SqlClient.SqlParameter("#gender", Predicate3))
End If
Command = New SqlClient.SqlCommand(BaseQuery & String.Join(" AND ", PredicateList.ToArray))
Command.Parameters.AddRange(ParameterList.ToArray)
COALESCE is your friend here. You can use it to make the where clause ignore comparisons where the parameter is NULL.
Select * from table Where (Name = COALESCE(#name,table.Name))
AND (Gender = COALESCE(#gender,table.Gender))
So, if the #name parameter is NULL, COALESCE(#name,table.Name) will return the value of the 'Name' column of the current row and (Name = COALESCE(#name,table.Name)) will always be true.
This assumes that if no value is entered in a textbox the corresponding parameter will be NULL. If instead it is a value such as 'None', you can use the NULLIF function to map 'None' to NULL
Select * from table Where
(Name = COALESCE( NULLIF( #name, 'None'), table.Name))
AND (Gender = COALESCE( NULLIF( #gender, 'None'), table.Gender))
How to implement a more efficient search?
The answer partly depends on what your definition of efficient is. I suspect you mean less code and fewer if blocks etc. But fundamentally, running a new SELECT * query to apply a filter is inefficient because your base data set can be all the rows and you just fiddle with the users View of it.
I have a DB with random data in columns for Fish, Color (string), Bird, Group (int) and Active which should be similar enough for Name, Age and Gender in the question - or that other long thing at the bottom.
DataTable
Fill a datatable and bind it to a DGV:
' form level object
Private dtSample As DataTable
...
' elsewhere
Dim sql = "SELECT Id, Name, Descr, `Group`, Fish, Bird, Color, Active FROM Sample"
Using dbcon As MySqlConnection = New MySqlConnection(MySQLConnStr)
' create SELECT command with the Query and conn
Dim cmd As New MySqlCommand(sql, dbcon)
...
daSample.Fill(dtSample)
daSample.FillSchema(dtSimple, SchemaType.Source)
End Using
dgv2.DataSource = dtSample
Going forward, we can filter the user's view of that table without issuing a new query.
Filter Controls
If some of the fields are limited to certain selections, for instance Gender, you can use a ComboBox instead of a TextBox. This is to help the user succeed and avoid typos (Make or Mael instead of Male; or here, correctly spelling Baracuda I mean Baraccuda, er Barracuda correctly.
For illustration purposes, Fish is something where the user can type in anything at all, but Bird is constrained to a set of choices. If there is a Bird table, cboBird can be bound or populated from it. But you may also be able to populate it from the master/base table:
Dim birds = dtSample.AsEnumerable.Where(Function(d) d.IsNull(5) = False).
Select(Function(d) d.Field(Of String)("Bird")).
Distinct.
ToArray()
cboBird.Items.AddRange(birds)
If "Finch" is a legal choice but there are none in the database, it wont show in the list. Depending on the app, this can be a Good Thing:
If the user filters on Finch and there a no resulting records, you won't need a MessageBox or StatusBar message explaining the empty result set.
If something is not in the list, you are signalling up front that there are none of those. It then becomes a matter of training why a known element isnt in the list.
On the other hand, you'd have to repopulate those filter controls each time before they are used in case new records were added recently. If the controls are on a Dialog or different TabPage, this is easy to do as needed.
It isnt always applicable, but it can help the user avoid typos.
It depends on the app whether either method is of value.
DBNull / 'none'
I am not sure why you are adding 'none' to each clause. If someone want to see all the 'John` or all the 'Cod' records, it doesn't seem like they would also be interested in 'none'. Personally, Null/DBNull seems a better way to handle this, but it is easy to add or not add either form.
It would seem more valuable to filter to just those with DBNull/None. The code above for the Bird List filters out DBNull and I would do so for none as well. Then, before the result is added to the ComboBox, add a `None' item first so it is at the top.
Again it depends on what the app does; Or = 'None', may make perfect sense in this case.
Filter
Using a TextBox for Fish and Group, a ComboBox for Bird and Color and a CheckBox for Active, the code can form the filter thusly:
Dim filterTerms As New List(Of String)
Dim filterFmt = "{0} = '{1}' "
' OR:
' Dim filterFmt = "{0} = '{1}' OR {0} Is Null"
' OR:
' Dim filterFmt = "{0} = '{1}' OR {0} = 'none'"
If String.IsNullOrEmpty(tbSearchFish.Text) = False Then
Dim txt = tbSearchFish.Text.Replace("'", "''")
filterTerms.Add(String.Format(filterFmt, "Fish", txt))
End If
If cboBird.SelectedIndex > -1 Then
filterTerms.Add(String.Format(filterFmt, "Bird", cboBird.SelectedItem.ToString))
End If
If String.IsNullOrEmpty(tbGroup.Text) = False Then
Dim n As Int32
If Int32.TryParse(tbGroup.Text, n) Then
filterTerms.Add(String.Format(filterFmt, "[Group]", n))
End If
End If
If cboColor.SelectedIndex > -1 Then
filterTerms.Add(String.Format(filterFmt, "Color", cboColor.SelectedItem.ToString))
End If
If chkActive.Checked Then
' NOTE: I do not have TreatTinyAsBoolean turned on
' for some reason
filterTerms.Add(String.Format(filterFmt, "Active", "1"))
End If
If filterTerms.Count > 0 Then
Dim filter = String.Join(" AND ", filterTerms)
dtSample.DefaultView.RowFilter = filter
Dim rows = dtSample.DefaultView.Count
End If
Use whichever filterFmt is appropriate for what the app needs to do
A filter term is only added to the list if the related control has a value (as per above, this could include a 'None').
For the TextBox, it escapes any embedded ticks such as might be found in names like O'Malley or D'Artgnan. It replaces one tick with two.
Since Group is a numeric, a valid Int32 input is tested
If there are elements in the filterTerms list, a filter string is created
The filter is applied to the DefaultView.Filter (you can use also use a DataView or a BindingSource) so that the code need not query the database to provide filter capabilities.
Rows will tell you how many rows are in the current View.
The only halfway tricky one is a Boolean like Gender or Active because those actually resolve to three choices: {Any/Either, A, B}. For that, I would use a ComboBox and ignore it for SelectedIndex 0 as well. I didn't bother with this because the Combo concept is amply covered. Result:
Is it More "Efficient"?
It still depends.
It doesn't re-query the database to get rows the app can already have.
No new DBConnection, DBCommand or other DBProvider objects are created, just a list.
No need to dynamically create a SQL statement with N parameters in a loop to avoid SQL injection/special words and chars.
It doesn't even query the database for the items for the filter terms. If there is a static list of them in the DB, they could be loaded once, the first time they use the filters.
It is easy to remove the filter, no need to query yet again without WHERE clauses.
A ComboBox where applicable helps the user find what they want and avoid typos.
Is the SQL "cleaner". more "efficient? The code doesn't really mess with new SQL, just some WHERE clauses.
Is there less code? I have no idea since we just see the result. It doesnt string me as a lot of code to do what it does.
In my database there are 3 column which is Name, Age, Gender. In the program, I only want to use 1 search button. When the button is clicked, the program determine which 3 of the textbox has input and search for the right data.
And when only name is entered, I only query for the name. Must I check textbox by textbox whether there is user input and then write multiple query for each of them? Or is there a better way to do this?
SELECT * FROM `table`
WHERE (`name` = #name AND `name` IS NOT NULL)
OR (`age` = #age AND (`age`>0 OR `age` IS NOT NULL))
OR (`gender` = #gender AND `gender` IS NOT NULL);
With the above query if all text boxes have value, the result will not be one record (as if you where using logical AND between fields). If you want only that record you will filter it server-side with php from the rest of the results.
You can check the results on your own in this Fiddle
EDIT
In order to solve the above inconvenience (not bringing easily single results when needed) i got a little help from this answer and re-wrote the above query as:
SELECT *, IF(`name`=#name, 10, 0) + IF(`age`=#age, 10, 0) + IF(`gender`=#gender, 10, 0) AS `weight`
FROM `table`
WHERE (`name` = #name AND `name` IS NOT NULL)
OR (`age` = #age AND (`age`>0 OR `age` IS NOT NULL))
OR (`gender` = #gender AND `gender` IS NOT NULL)
HAVING `weight`=30;
OR to still get all records with a weight on result
SELECT *, IF(`name`=#name, 10, 0) + IF(`age`=#age, 10, 0) + IF(`gender`=#gender, 10, 0) AS `weight`
FROM `table` WHERE (`name` = #name AND `name` IS NOT NULL)
OR (`age` = #age AND (`age`>0 OR `age` IS NOT NULL))
OR (`gender` = #gender AND `gender` IS NOT NULL)
ORDER BY `weight` DESC;
You were pretty close. Let's look at
(FloatNo = #floatNo OR FloatNo = 'None')
So you want the field either to be the given input or 'None'? But there are (supposedly) no records in your table with FloatNo 'None'. What you really want to do is find out whether the input is none (i.e. empty):
(FloatNo = #floatNo OR #floatNo = '')
And for the case the user types in a blank by mistake, you can ignore this, too:
(FloatNo = #floatNo OR TRIM(#floatNo) = '')
The whole thing:
myCommand = New MySqlCommand(
"Select * from project_record Where
(FloatNo = #floatNo OR TRIM(#floatNo) = '') AND
(DevCompanyName = #devCompanyName OR TRIM(#devCompanyName) = '') AND
(DevType = #devType OR TRIM(#devType) = '') AND
(LotPt = #lotPt OR TRIM(#lotPt) = '') AND
(Mukim = #mukim OR TRIM(#mukim) = '') AND
(Daerah = #daerah OR TRIM(#daerah) = '') AND
(Negeri = #negeri OR TRIM(#negeri) = '') AND
(TempReference = #tempRef OR TRIM(#tempRef) = '')", sqlConn)
What is wrong with your approach?
Just change
(FloatNo = #floatNo OR FloatNo = 'None')
to
(FloatNo = #floatNo OR FloatNo = '' or FloatNo IS NULL)
And do that for every criteria.
Your query will respect empty values and NULL values after that.

DLookup Or DMax To Find Value

I am sure this is fairly simple put I am having trouble getting started on this. I use a Form to invoice clients which includes the field [Billing_Month]. What I'm looking to accomplish is this. When I create a new invoice, the [Billing_Month] will look to the last invoice created (use [Invoice_#] with DMax?), and populate the value from that that invoices [Billing_Month]
I have thought to use: Billing_Month = DMax ("Billing_Month", "frmInvoices"), but this doesn't specifically get me the last invoice, it would just look for the highest Billing_Month, which is a text field.
I have thought to use: Billing_Month = DLookup ("Billing_Month", "frmInvoices"), But this doesn't get me the last invoice to pull from.
I'd use a custom function for this - assuming the underlying table is called tblInvoices:
Function GetBillingMonthOfLatestInvoice()
Const SQL = "SELECT TOP 1 Billing_Month FROM tblInvoices ORDER BY [Invoice_#] DESC"
Dim RS AS DAO.Recordset
Set RS = CurrentDb.OpenRecordset(SQL)
If RS.EOF Then
GetBillingMonthOfLatestInvoice = Null
Else
GetBillingMonthOfLatestInvoice = RS(0)
End If
End Function
Update
The above code can be generalised to return other related fields like so:
Function GetValueForLatestInvoice(FieldToLookUp As String)
Dim RS As DAO.Recordset, SQL As String
SQL = "SELECT TOP 1 " + FieldToLookUp + " FROM tblInvoices ORDER BY [Invoice_#] DESC"
Set RS = CurrentDb.OpenRecordset(SQL)
If RS.EOF Then
GetValueForLatestInvoice = Null
Else
GetValueForLatestInvoice = RS(0)
End If
End Function
To use, copy the code to a new standard module, then for each relevant text box on the form, set its Default Value property in the Properties window to something like this:
=GetValueForLatestInvoice("Billing_Month")
That would be for the text box holding the billing month value; for the one holding the billing year, you would use
=GetValueForLatestInvoice("Billing_Year")
You can use a combination of both DLookup() and DMax() like so:
DLookup("Billing_Month","tblInvoices","[Invoice_#]=" & DMax("[Invoice_#]","tblInvoices"))

combobox rowsource based on forms record source (distinct) field

I have a form record source set to a elaborate SQL select statement. That is working fine. If it helps to know, the form layout is Tabular. Here is an example of the data:
order carrier billto employee
1 smgd horm chrnic
2 axxm sele chrnic
3 smgd horm redned
4 mcta cron greand
5 mcta cron greand
Its basically unbilled order entries. I want a combo box to show distinct employee names (chrnic, redned, greand) based on the current records showing. I will be coding it to filter the form. Seems simple, but I am having trouble
Things I have tried:
Tried setting rowsource to me.recordsource, but get an
It appears that I would need to parse & edit that string
I copied the complex query & put as combo box record source & that worked to filter the form, so I know that filter logic is correct. I just want it to be dynamic so we only have to change SQL statement in one place if needed
"I have a form record source set to a elaborate SQL select statement."
Save that query as a named QueryDef. I will pretend you chose qryRecordSource as the name.
"I want a combo box to show distinct employee names ... based on the current records"
For the combo box row source use ...
SELECT DISTINCT employee
FROM qryRecordSource
ORDER BY 1;
And then to filter the form based on the combo selection, add a command button, cmdApplyFilter, and use this in its click event procedure ...
Me.Filter = "[employee] = '" & Me.YourComboName.Value & "'"
Me.FilterOn = True
If the employee names can include an apostrophe, use this for the Filter expression ...
Me.Filter = "[employee] = '" & _
Replace(Me.YourComboName.Value, "'", "''") & "'"
If you want to include a combo row to clear the filter, use a UNION query as the combo row source ...
SELECT "*** ALL ***" AS employee
FROM Dual
UNION
SELECT employee
FROM qryRecordSource
ORDER BY 1;
... where Dual is any table or query which returns just one row. Then in the command button click event you can do ...
If Me.YourComboName.Value = "*** ALL ***" Or _
IsNull(Me.YourComboName.Value) Then
Me.Filter = vbNullString
Me.FilterOn = False
Else
Me.Filter = "[employee] = '" & Me.YourComboName.Value & "'"
Me.FilterOn = True
End If
And actually you wouldn't even need the command button. You could set the Filter from the combo's AfterUpdate event.

Combobox issue in Access VBA

I am trying to set a combobox's value to the default one, the problem is the data source is from a query that return an integer type , I want my default value to be "*", when I try this :
Private Sub LabelWklstID_DblClick(Cancel As Integer)
Me.WorklistIDSelector.Value = Mid(Me.WorklistIDSelector.DefaultValue, 2, 1)
End Sub
it didn't work getting " Invalid value " error, but when I try an int it works :
Me.WorklistIDSelector.Value = 1
How can I make my combobox accept the "*". Any Help will be appreciated
Edit:
RowSource=
SELECT tWorkList.WorkListID, tWorkList.ProjectID FROM tWorkList GROUP BY tWorkList.WorkListID, tWorkList.ProjectID HAVING (((tWorkList.ProjectID)=[Forms]![fMain]![ProjectID])) ORDER BY tWorkList.WorkListID;
Bound Column = 1
Column Widths =2,54cm
select tworklistID as ID, other fields from tworlklist etc
UNION
select '*" as ID, 0,0,0(dummy blank other fields)