Sometimes we need to process the selected item Value Based on ComboBox (same as ListBox), but the item of ComboBox in Delphi is a tstrings object, we cannot inherit from the ComboBox option class as in C # or Java, and create a class we need to complete the task. However, the following solutions are found in the ComboBox object of Delphi:
Create a new class to store the required data:
Titemex = Class (tobject) caption: string;
Public
Stringvalue: string;
End;
// Fill the ComboBox with the value in adoquery
Function fillincomboboxwithadoquery (objadoquery: tadoquery; objcombobox: tcombobox; SQL: string; captionfieldname: string; valuefieldname: string; noasfirst: Boolean): Boolean;
// If noasfirst is true, the first entry of ComboBox is 'none'
VaR
Objitemex: titemex;
Begin
Objcombobox. Clear;
Objcombobox. itemindex: =-1;
If noasfirst
Then begin
Objitemex: = titemex. Create;
Objitemex. Caption: = 'none ';
Objitemex. stringvalue: = '';
Objcombobox. Items. addobject (objitemex. Caption, objitemex );
Objcombobox. itemindex: = 0;
End;
Objadoquery. close;
Objadoquery. SQL. Clear;
Objadoquery. SQL. Add (SQL );
Objadoquery. open;
Objadoquery. first;
While not objadoquery. EOF do
Begin
Objitemex: = titemex. Create;
Objitemex. Caption: = objadoquery. fieldbyname (captionfieldname). asstring;
Objitemex. stringvalue: = objadoquery. fieldbyname (valuefieldname). asstring;
Objcombobox. Items. addobject (objitemex. Caption, objitemex );
Objadoquery. Next;
End;
Objadoquery. close;
Result: = true;
End;
// Obtain the selected orientation in comboobx
Function getcomboboxselectedstringvalue (objcombobox: tcombobox): string;
VaR
Objitemex: titemex;
Begin
If (objcombobox. itemindex>-1)
Then begin
Objitemex: = (objcombobox. Items. objects [objcombobox. itemindex] As titemex );
Result: = objitemex. stringvalue;
End
Else begin
Result: = '';
End;
End;
The ListBox solution is similar to this one.
(Www.sinoprise.com)