Get ID Filed from a Combobox in a Text Box where 1

2019-06-09 23:46发布

问题:

I have a form, where I want to implement cascading combo-box.

1st user selects "Client Name" where I have SQL statement getting 3 columns - CLient ID, Client First Name and Client Last Name. In order to allow users to enter First Name, instead of ID, have set the Column Width: 0;3

2nd then user selects "Work" where I have SQL statement getting 2 columns - Work ID, Work description. In order to allow users to enter Work description, instead of ID, have set the Column Width : 0;2

Want to cascade the list, so that "Work" list in combo-box only shows the Work table has a foreign key to Client ID.

I implemented the cascading combo-box by adding SQL Statement to Row Source of work Combo-box.

SELECT WorkTbl.WorkID, WorkTbl.WorkDescription, WorkTbl.ClientID 
FROM WorkTbl 
WHERE (((WorkTbl.ClientID)=Forms![Work Done Entry]!cboClientID);

"cboClientID" is name of the Combo-box of Client.

But since the User will be entering in "Client Name" instead of "Client ID" because of have set the Column Width: 0;3 on cboClientID. Hence the SQL Query is not working.

Is there any work around? One solution, which i found (But could not make it work) was to add a Text-box and set Client ID in this Text-Box and then make us of this Text box to get the client ID required in the SQL. Got this idea form This Question

Thanks in advance for answering this Question. Any help or suggestion appreciated.

回答1:

How about you use the "on after update" event of your "CboclientID" combobox?

just add this code to your "cboClientID" combobox on after update event:

Dim SQL_GET As String
SQL_GET = "SELECT WorkTbl.WorkID, WorkTbl.WorkDescription From WorkTbl WHERE (((WorkTbl.ClientID)=" & Nz(Me.cboClientID.Value, 0) & ");"
Me.cboWork.RowSource = SQL_GET

this way every time when you update your client name your work combobox will also change according to your selection. hope this helps.



回答2:

You SQL statement should work as it is. The SQL will use the Value property of the Combobox control for the query and that will contain the ClientId as that is the first column in your combobox data.

However the SQL to populate the work combobox will be executed when you first open your form and there is no client selected. Hence the SQL will not return any data and the work combobox stays empty.

To make this work as intended, you have to requery the work data whenever you select another client. One way to do this is, writing an event procedure for the After Update Event of the client combobox. In the properties of the client combobox go to Events, After Update and select [Event Procedure]. Then add VBA code similar to this to the class module of the form.

Private Sub cboClient_AfterUpdate()
    Me.cboWork.Requery
End Sub