I have a table of clients. Each Client has an ID. I'm loading a combobox from SQL Server and only displaying Firstname and LastName. I created this simple select statement.
sql= Select ID, FirstName, LastName
sql =From dbo.tblClients order by LastName
g_rs.open, sql, g_Database
cboNames.AddItem vbNullString
cboNames.ItemData(cboNames.NewIndex) = 0
While Not g_RS.EOF
cboNames.AddItem g_RS("LastName") & ", " & g_RS("FirstName") &
g_RS.MoveNext
Wend
My question is in regards to when I actually choose a name from the combo box. How do i know the ID that's assigned to that client.
You aren't assigning the ItemData in your loop. Your code should look like:
While Not g_RS.EOF
cboNames.AddItem g_RS("LastName") & ", " & g_RS("FirstName")
cboNames.ItemData(cboNames.NewIndex) = g_RS("ID")
g_RS.MoveNext
Wend
Then, in other code you can retrieve the ID from the selected item's ItemData:
Private Sub cboNames_Click()
Dim selectedID as Integer
If cboNames.ListIndex > 0 Then
selectedID = cboNames.ItemData(cboNames.ListIndex)
End If
End Sub
Related
I have an Access database with about 500,000 records. There is a specific column which has the transaction reference.
This is of the form:
Transaction_Ref
CDY1053N1
CDY1053N2
CDY1053N3
JFD215D1
JFD215D2
Where CDY1053N and JFD215D are customer references, and the 1,2,3, etc which follows is the transaction number.
What I am looking for is a loop which will update a column called "Group". This will go to row 1, and loop through the database to find transaction references similar to CDY1053N and assign a group ID, for example:
Transaction_Ref Group_ID
CDY1053N1 1
CDY1053N2 1
CDY1053N3 1
JFD215D1 2
JFD215D2 2
Any ideas please?
Thanks for the help.
This might not be the best or most elegant way to do this (particularly with the number of records you have), but this worked on my small set of test records.
I've assumed Transaction_Ref and Group_ID are in the same table and I've called that table tblTransactions.
I've also assumed that you might want to run this on new data so have nulled the Group_ID before looping through and resetting the values. This could mean that a different value for Group_ID gets assigned for a group of records (for example, were your records change order between subsequent runs of this sub).
If that's a problem you'll need to tweak this a bit.
Public Sub AssignGroupID()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sql As String
Dim i As Integer
Set db = CurrentDb
' Clear the Group_ID column (in case you want to run this more than once)
sql = "UPDATE tblTransactions Set Group_ID = Null"
db.Execute sql
' Open your table with the Transaction_Ref and Group_ID fields
Set rs = db.OpenRecordset("tblTransactions")
' Zero the counter
i = 0
' Start the loop (set it to end when it gets to the last record)
Do While Not rs.EOF
' Only update Group_IDs that haven't got a value yet
If IsNull(rs!Group_ID) Then
' Push the counter on
i = i + 1
' Update all Group_IDs with current counter number that
' match the customer reference of the current record
sql = "UPDATE tbltransactions Set Group_ID = " & i & " WHERE " _
& "Left(tblTransactions.Transaction_Ref, Len(tblTransactions.Transaction_Ref) -1) = '" _
& Left(rs!Transaction_Ref, Len(rs!Transaction_Ref) - 1) & "'"
db.Execute sql
End If
' Move to the next record
rs.MoveNext
Loop
'clean up
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
What's the matter. After selecting a name from a ComboBox in ListBox have to display all the employees of the chosen company. And now my problem, always in a ListBox displays only 2 employees of the chosen company. The following piece of code responsible for displaying. For the record, I'm new in VBA. And of course, my question is why only two employees?
Procedure-click on the selected company from ComboBox:
Dim RecordSt As Recordset
Dim db As Database
Dim query As String
Dim strKombi30 As String
Dim i As Integer
strKombi30 = Me.Kombi30.Value ''combobox
query = "SELECT [Employees].[First name], [Employees].[Name] FROM" & _
"[Employees] WHERE [Employees].[Company] = '" & Me.Kombi30
Set db = CurrentDb()
Set RecordSt = db.OpenRecordset(query)
RecordSt.MoveFirst
For i = 0 To RecordSt.RecordCount
listContacts.AddItem (RecordSt.Fields("First name").Value & " " & RecordSt.Fields("Name").Value)
RecordSt.MoveNext
Next i
strKombi30 = Me.Kombi30.Value ''combobox
query = "SELECT [Employees].[First name], [Employees].[Name] FROM" & _
"[Employees] WHERE [Employees].[Company] = '" & strKombi30 & "'"
I am getting a huge amount of data from my database which I before iterated through in a recordset like this:
sql = "select * from table"
set rs = conn.execute(sql)
if not rs.eof then
do until rs.eof
id = rs("id")
fullname = rs("fullname")
response.write("<a href='/" & id & "'>Hi " & fullname & ".<br />")
rs.movenext
loop
Now I am using a static recordset using GetRows() like this:
sql = "select * from table"
set rssql = conn.execute(sql)
if not rssql.eof then
rs = rssql.getrows()
end if
rssql.close
if isarray(rs) then
for counter = lbound(rs) to ubound(rs)
id = rs(0, counter)
fullname = rs(1, counter)
response.write("<a href='/" & id & "'>Hi " & fullname & ".<br />")
next
end if
Is it really not possible to do something like rs("id", counter) instead of using static numbers? I have a dynamic amount of coloumns (created by the system) in my table and it is very dynamic which of them I need. The number of coloumns I need in each rows are specificed by another coloumn in the row.
GetRows returns a vanilla array & as such is only addressable by a numeric index.
If you feel you need to dispose of the connection as soon as possible for some reason, you can fully populate the recordset and disconnect is as describe here.
(You can always use the initial recordset to populate another array or collection with the column names via the .Fields collection)
rs.Fields(counter).Name will give you access to column names. Unfortunately getrows() does not create an associative array, so you cannot look up data by column name.
Hey all i am in need of some ideas on how to go about doing the following:
I have a textbox that a user can type in an ID to search for in a database. It currently just checks for 1 ID.
Example:
User types in ID 645378
The Query would look like:
SELECT * FROM blahTable WHERE theID = '645378';
Now, i am looking to allow the user to type in more than 1 ID at a time and display those results.
So again an example would be:
User types in ID(s): 645378, 78664, 901524
And now this is where my question comes into play. How can i create a query based on how many ID's the user inputs into the textbox?
Any help would be great!
David
You could use the IN statement in SQL.
SELECT * FROM blahTable where theID in ('123','456','789')
I would advise implementing this via a parametrized query to avoid Bobby Tables (SQL Injection)
Just use IN:
SELECT * FROM blahTable WHERE theID IN (645378, 78664, 901524);
Note that if your values are actual strings and not numbers, then it will require some additional work:
Dim asValues As String()
Dim sbQuery As New System.Text.StringBuilder(5000)
' Get the text, but remove any embedded semi-colons and single quotes for sql injection'
asValues = Miles.Text.Replace(";", " ").Replace("'", " ").Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries)
sbQuery.Append("SELECT * FROM blahTable WHERE theID IN (")
Dim fUseComma As Boolean
' Add each value to the query string. In this case, we are wrapping with '
For Each sValue As String In asValues
' Test the value for reasonableness (example only)'
If IsNumeric(sValue) Then
' Only use the comma starting from the second valid item added
If fUseComma Then
sbQuery.Append(",")
Else
fUseComma = True
End If
sbQuery.Append("'").Append(CInt(sValue)).Append("'")
End If
Next
sbQuery.Append(")")
cmd.CommandText = sbQuery.ToString
try this thing.
Dim xIDList As String = "645378, 78664, 901524" 'the user should separate ID by COMMA
Dim xID() As String = xIDList.Split(CChar(",")) 'splits the xIDlist
Dim xIDforQuery As String = String.Empty
For Each oID As String In xID
If oID.Trim.Length <> 0 Then
xIDforQuery &= "," & " '" & oID & "'" ' if ID is not numeric
' xIDforQuery &= "," & oID.ToString ' use this line if ID is numeric
End If
Next
xIDforQuery = xIDforQuery.Trim
xIDforQuery = CStr(IIf(Mid(xIDforQuery, 1, 1) = ",", Mid(xIDforQuery, 2, xIDforQuery.Length - 1), xIDforQuery))
Dim xFinalQuery As String = String.Empty
xFinalQuery = String.Format("SELECT * FROM blahTable where theID in ({0})", xIDforQuery)
' xFinalQuery is the final query statement but this approach is vulberable to SQL Injection.
How do users know which ID's they want? If there aren't too many ID's, using a multiple-selection list-box would improve the UI and simplify the code. If there are too many, then you might consider using an auto-complete text-box for users to choose items that can then be copied (removed) from a list-box to be used by the query.
In a SQL database I have a table, Table1. This table is related to another table, Table2 which in turn is related to Table3. There is a query Query1 that selects certain records from Table1.
This database is linked to in an Access database project
A form Table1Data is based on Table1, with a datasheet containing related Table2 data (and subsequently Table3 data). This form is opened by another form (Switchboard). The problem comes when the form is opened. I want the form to be filtered, but when I set up a macro and open the form and set the Filter to Query1, the data in the form is not filtered. Why does this happen, is this not the way to do it? Query1 selects all the columns from Table1, so mismatching columns should not be an issue.
Additionally I want to lock it down - only certain people can execute Query1, same with other queries (Query2, Query3 etc). So they can only edit the data that they are permitted to edit.
My preferred solution is to set the recordsource in the Form Open event. This gives me the most control over what is going on.
Here is my boilerplate for doing this. It also includes looking up the OpenArgs which are passed on calling the form. You can just comment out or remove the If/Then statement if you aren't looking to specify anything from the calling form in your SQL.
Private Sub Form_Open(Cancel As Integer)
' Comments :
' Parameters: Cancel -
' Modified :
' --------------------------------------------------
On Error GoTo Err_Form_Open
Dim strSQL As String
Dim strVariable As String
Dim strDateVariable As String
Dim dteDateVariable As String
Dim i As Integer
Dim n As Integer
'Get variables from Left and right of | in OpenArgs
If Not (IsNull(Me.OpenArgs)) Then
i = InStr(1, Me.OpenArgs, "|")
n = Len(Me.OpenArgs)
strVariable = Left(Me.OpenArgs, n - (n - i + 1))
strDateVariable = Right(Me.OpenArgs, (n - i))
dteDateVariable = CDate(strDateVariable)
Else
GoTo Exit_Form_Open
End If
strSQL = "SELECT ... " _
& "FROM ... " _
& "WHERE (((Field1)='" & strVariable & "') " _
& " AND ((Field2)=#" & dteDateVariable & "#));"
Me.RecordSource = strSQL
Me.Requery
Exit_Form_Open:
Exit Sub
Err_Form_Open:
Select Case Err.Number
Case Else
Call ErrorLog(Err.Number, Err.Description, "Form_Open", "frmName", Erl)
GoTo Exit_Form_Open
End Select
End Sub