MS Access - Autofill not work in combo box - ms-access

I've created a combo box and the data will be populated from SQL Server, but I found that the autofill function of this combo box is not working. Is there any problem in my code ? Thanks.
Dim oCon As ADODB.Connection
Dim oRec As ADODB.Recordset
Dim strQuery As String
Set oCon = New ADODB.Connection
Set oRec = New ADODB.Recordset
oCon.Open "connection string"
strQuery = "select statement"
oRec.Open strQuery, oCon, adOpenKeyset, adLockOptimistic
Me.cbxUser.RowSourceType = "Table/Query"
Set Me.cbxUser.Recordset = oRec
Updated on 16 Jan 2018
It seems that the problem is resolved by using ComboBox.AddItem method. But I don't know why the autofill function is not working when I use Set Me.cbxUser.Recordset = oRec
Set oRec = oCon.Execute(strQuery)
Me.cbxUser.RowSourceType = "Value List"
Do While Not oRec.EOF
Me.cbxUser.AddItem (oRec("UserID"))
oRec.MoveNext
Loop
GIF file

The RowSource SQL string must contain the clause "DISTINCT" to make all the business to work (I read this interesting statement in another developer's response in other forum, I tried it and it works)
Also, do not try to transform a list box into a combo box. The properties of the combo box AutoExpand and LimitToList will not convince the combo to work as expected.

Related

Cant get data from a specific Table in MySQL to a Vb.net Combo box

So here's my problem, I have a combo box that I want to fill with data from a table in MySql on load. I used this code for doing that:
Dim strSQL As String = "SELECT containers FROM tbl_items_containers"
Dim da As New MySqlDataAdapter(strSQL, SQLConnection)
Dim cmd As New MySqlCommand
Dim ds As New DataSet
SQLConnection.ConnectionString = ServerString
cmd.Connection = SQLConnection
da.Fill(ds, "tbl_items_containers")
With cb_container_type
.DataSource = ds.Tables("tbl_items_containers")
.DisplayMember = "containers"
.ValueMember = "containers"
.SelectedIndex = 0
End With
The error shown whenever i run it is:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.
Now here's the thing, I tried getting data from another table in the same database and the code worked. My combo box was populated with data. I assumed that the problem is in the database, But I'm really lost here. I have no idea what to do. Any Ideas as to what may have cause the error? Thanks in advance.

GetRows on a RecordSet won't store text column from Access DB

I've successfully connected to my Access database from excel, and can return the contents of the database in a string Using GetString on my RecordSet. GetString prints all of the contents of the table into a message box as I expect it to(in comments below), but GetRows ignores one of the columns(GCAT in this case), which happens to be the only text field in the database. I am trying to print a particular instance of this field into my excel sheet, but at array position(0,1), where the GCAT field should be, it prints the third item of the record, and not the second as I expect. What am I missing? Does it have something to do with it being a text field? Maybe i'm using the wrong library or database engine? Every other column in the database is returned normally.
Sub Connect()
Dim oConn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sConn As String
Dim sSQL As String
Dim arrayString As String
sConn = "Provider='Microsoft.ACE.OLEDB.12.0';Data Source='<path_to_db>'; Persist Security Info='False';"
' Open a connection.
Set oConn = New ADODB.Connection
oConn.ConnectionString = sConn
oConn.Open
' Make a query over the connection.
sSQL = "SELECT ID, GCAT, Min_Years, Max_Years, Contract_Price FROM GCAT"
Set oRs = New ADODB.Recordset
CursorLocation = adUseClient
oRs.Open sSQL, oConn, adOpenStatic, adLockBatchOptimistic, adCmdText
GCATArray = oRs.GetRows()
Sheets("Calculations").Range("D6").Value = GCATArray(0, 1)
'GCATString = oRs.GetString()
'MsgBox GCATString
' Close the connection.
oConn.Close
Set oConn = Nothing
End Sub
This is my first foray in VB so I'm both confused and struggling with the language to being with.
Can't see any obvious faults in your code, have you tried debugging yourself? You can loop the fields in the recordset, and display their names for testing like so:
For i = 0 To oRS.Fields.Count -1
debug.print oRS.Fields(i).Name
Next
That way, you can see whether the field you are looking for is actually there in the first place. Next, you can access the field your're after by doing:
Do While Not oRS.EOF
Debug.Print oRS!GCAT
'Exit Do 'if you want to display only the first, break out of the loop here
oRS.MoveNext
Loop
You don't need the GetRows() in this case, that should give you a performance boost too (very noticible on larger recordsets).

Save record changes - Access ado form

Help please!
I've created a database for logging service calls, based on one of Microsoft's templates (Very loosely based now!)
I have a "Case Details" form, which is opened from a case list split form. Originally, this was opening the form with a filter - which I assume means that it is actually loading the whole recordset?
As I assume (hopefully correctly) that this will be quite inefficient as the database grows, I decided to change the form to open and ADO recordset, using a SQL statement, only selecting the record I want.
The code for this is as follows, and the form opens with the correct record, and I can update the fields.
Private Sub Form_Load()
On Error GoTo Form_Load_Err
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
If (IsNull(TempVars!currentid)) Then
Me.DataEntry = True
Else
'Use the ADO connection that Access uses
Set cn = CurrentProject.Connection
'Create an instance of the ADO Recordset class,
'and set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT * FROM Cases WHERE ID = " & TempVars!currentid & ";"
.LockType = adLockOptimistic
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End If
Call IntializeCollections
Select Case (Me.Status)
Case 7, 8
Call EnableControls(mcolgrpAllFields, False)
End Select
Form_Load_Exit:
Exit Sub
Form_Load_Err:
MsgBox Error$
Resume Form_Load_Exit
End Sub
However, here is the problem. What the blinking heck do I do to save my changes? I've done some googling, and looked at MS Access Form Bound to ADO Disconnected Recordset but I'm still absolutely stumped.
Is there as simple "save the updates" command? or do I have to iterate through each field, check for changes, then save those changes?
Can someone please point me in the right direction?
Thanks in advance
If you need to update one record at a time try this solution for disconnected recordsets: http://www.techrepublic.com/blog/how-do-i/how-do-i-pass-data-over-a-network-using-disconnected-recordsets/

Run Time Error 3464: Data Type Mismatch in criteria expression

I have a form in Access 2010 with Two text boxes(AIPIDTxt to enter the search criteria and AIPResultTxt to display results) and a Button(Search button). I also have a Table Table1 in Access. When I click the Search Button, I need to execute a query whose criteria is in AIPIDTxt Textbox in the form, store the result in a recordset and display the results in the textbox AIPResultTxt. So I typed in the following VBA Code in the Button Event handler.
Private Sub SearchB_Click()
Dim localConnection As ADODB.Connection
Dim query As String
Dim aipid_rs As ADODB.Recordset
Dim db As Database
Set db = CurrentDb
Set localConnection = CurrentProject.AccessConnection
MsgBox "Local Connection successful"
query = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]=
" & [Forms]![AIPIDSearchF]![AIPIDTxt] & ""
Set aipid_rs = db.OpenRecordset(query)
Me.AIPResultTxt.Text = aipid_rs![AIP Name]
End Sub
But when I click the button I get Local Connection Successful Message Box and then a Run Time Error 3464 in the line:
Set aipid_rs= db.OpenRecordset(query)
I have searched for similar errors and made corrections. But the error keeps coming. Is there something wrong with my query? Couldn't figure out the error. The table is a local table. So I can directly give [Table1] and field names in the query in vba. Tried adding delimiters because the fields are text fields. But that didn't work as well. I could not give the following query as well:
query = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]= " & [Forms]![AIPIDSearchF]!
[AIPIDTxt].Text & ""
This gave me a run time error stating text cannot be referenced from controls that have lost focus. My criteria is text in the text box. The text box loses focus when i click the button. But when I googled for the error, solutions were to remove ".Text". So, I ended up with the above query. Do not know what is wrong with the line:
Set aipid_rs= db.OpenRecordset(query)
I suspect you have more than one problem with that code. But Access complains about only the first problem it finds. Look again at these 2 lines ...
Dim aipid_rs As ADODB.Recordset
Set aipid_rs = db.OpenRecordset(query)
OpenRecordset is a DAO method which returns a DAO recordset. But the code attempts to assign it to aipid_rs which was declared As ADODB.Recordset. Those recordset types are not compatible.
There is an ADO connection object variable, localConnection, which is not used for anything later. Although it doesn't trigger an error, it's just not useful. And actually I don't see any reason to use anything from ADO for this task.
I suggest you try this version of your code ...
'Dim localConnection As ADODB.Connection
'Dim query As String ' query is a reserved word
Dim strQuery As String
'Dim aipid_rs As ADODB.Recordset
Dim aipid_rs As DAO.Recordset
Dim db As Database
Set db = CurrentDb
'Set localConnection = CurrentProject.AccessConnection
'MsgBox "Local Connection successful"
' you said [AIP ID] is text type, so include quotes around
' the text box value
strQuery = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]= '" & _
[Forms]![AIPIDSearchF]![AIPIDTxt] & "'"
Debug.Print strQuery
DoCmd.RunCommand acCmdDebugWindow
Set aipid_rs = db.OpenRecordset(strQuery)
'Me.AIPResultTxt.Text = aipid_rs![AIP Name] ' .Text property is only
' available when control has focus; it will trigger
' an error at any other time
Me.AIPResultTxt.Value = aipid_rs![AIP Name]
Note Debug.Print strQuery will display the text of the SELECT statement in the Immediate window, and DoCmd.RunCommand acCmdDebugWindow opens the Immediate window. If you still have a problem with the query, copy the statement text and paste it into SQL View of a new query for testing.
Finally I'm curious whether this might give you what you need with much less code ...
Private Sub SearchB_Click()
Me.AIPResultTxt.Value = DLookup("[AIP Name]", "Table1", _
"[AIP ID]='" & Me.AIPIDTxt & "'")
End Sub
You are using an ADO recordset, therefore your open syntax is incorrect. The following should work for you (except you may get an error setting the text if the control doesn't have focus...)
Dim localConnection As ADODB.Connection
Dim query As String
Dim aipid_rs As ADODB.Recordset
Dim db As Database
Set db = CurrentDb
Set localConnection = CurrentProject.AccessConnection
MsgBox "Local Connection successful"
query = "SELECT [AIP Name] FROM [Table1] WHERE [AIP ID]= '" & [Forms]![AIPIDSearchF]![AIPIDTxt] & "'"
'Set aipid_rs = db.OpenRecordset(query)
Set aipid_rs = New ADODB.Recordset
aipid_rs.Open query, localConnection, adOpenStatic, adLockReadOnly
If Not aipid_rs.EOF Then
Me.AIPResultTxt.Text = aipid_rs![AIP Name]
Else
MsgBox "No records!!"
End If
aipid_rs.Close
Set aipid_rs = Nothing
localConnection.Close
Set localConnection = Nothing
db.Close
Set db = Nothing
OK, So I have been searching for a simple search element for quite awhile...
I have tried using subforms and I have tried recordsets. All of these have given me the information. But not the compactness I was looking for, thanks!!!
using the DOA stuf is great but not for my application.
using the above:
Me.AIPResultTxt.Value = DLookup("[AIP Name]", "Table1", _
"[AIP ID]='" & Me.AIPIDTxt & "'")
I have the compactness of code I was looking for...
THanks!!!
T

Add query to child form

I have been looking for some time now, but I can't see the problem here:
Option Compare Database
Option Explicit
Private Sub cmd_Refresh_Click()
Dim sSQL_Select As String
Dim Qdb As Database
Dim Qry As QueryDef
sSQL_Select = "SELECT * FROM T_TIME_SCHEDULE"
Set Qdb = CurrentDb
Set Qry = Qdb.CreateQueryDef("QTS", sSQL_Select)
DoCmd.OpenQuery "QTS", acViewNormal
Me.F_Child_Result.Form.RecordSource = "QTS"
Me.F_Child_Result.Requery
Qdb.QueryDefs.Delete ("QTS")
Set Qdb = Nothing
End Sub
This line:
Me.F_Child_Result.Form.RecordSource = "QTS"
results in the following error:
Run-Time error '2467': The expression you entered refers to an object that is closed or doesn't exist.
The syntax should be correctly constructed, and I double checked the name of the subform.
Desipte, the error remains.
Do not set the record source to a query, just the SQL string.
sSQL_Select = "SELECT * FROM T_TIME_SCHEDULE"
''Set Qdb = CurrentDb
''Set Qry = Qdb.CreateQueryDef("QTS", sSQL_Select)
''DoCmd.OpenQuery "QTS", acViewNormal
Me.F_Child_Result.Form.RecordSource = sSQL
''Me.F_Child_Result.Requery
There is no need to requery, the form will be requeried when the record source is changed.
Note that even if you could set the record source to a query (which you can't), it would not be quoted.
FROM Chat
It appears that there are two mixed strands in the question. What is required is a means to set the Source Object of the subform control to a query, not the Record Source of a form contained by the subform control.
The source object can be set like so:
Me.F_Child_Result.SourceObject="Query." & sQueryName
If the Source Object is already set to the name of a saved query that is used only for this form, there is no need to reset it, you can just modify the sql of the query:
Set qdf = CurrentDB.QueryDefs("JunkQuery")
qdf.SQL = sSQL