TDBLookupComboBox/fr

From Lazarus wiki
Jump to navigationJump to search

English (en) français (fr)

TDBLookupComboBox tdblookupcombobox.png est un TComboBox lié aux données (doublement). Il peut être trouvé sur l'onglet Data Controls de la palette de composants.

Le contrôle TDBLookupCombobox obtient une liste de valeur depuis sa ListSource qui représente la donnée d'une autre table (p.ex. des produits). Alors, il

  • affiche les valeurs dans la ListField (p.ex. le champ "NomDeProduit")
  • se rappelle des valeurs dans la propriété KeyField (p.ex. un champ "ID")

Le ComboBox stocke le résultat (i.e. la valeur KeyField) dans la propriété DataField, p.ex. le champ "ProduitID" dans la propriété DataSource (p.ex. une table "Commandes").

La différence avec le TDBComboBox est que le TDBComboBox est un "contrôle individuellement lié aux données" (en quelque sorte).

Utilisation sans liaison

Vous pouvez obtenir la combobox pour rechercher des valeurs d'une table sans enregistrer les résultats dans une autre en laissant les propriétés DataSource et KeyField 'vides.

L'extrait de code exemple suivant :

  • permettra à un TDBLookupComboBox d'être configuré en mode non lié (i.e. sans aucun changement porté dans la base de données)
  • Assurera que les données visibles dans le TDBLookupComboBox sont issues de l'enregistrement sélectionné dans le DataSet (i.e. en choisissant une nouvelle valeur dans le TDBLookupComboBox défilera le DataSet vers l'enregistrement correct)
  • Définira la valeur initiale affichée dans le TDBLookupComboBox et l'enregistrement sélectionné dans le DataSet pour les valeurs précédemment mémorisées.

L'extrait de code exemple suivant NE :

  • mettra PAS à jour automatiquement la valeur du TDBLookupComboBox si la DataSet est défilé (vous avez besoin d'ajouter votre propre gestionnaire au Dataset.OnScroll pour accomplir ceci)
interface
  type
    TForm1 = class(TForm)
      cboLookup: TDBLookupComboBox;
      dsSource: TDatasource;
      dsetSource: TDataset;
      ...
    protected
      FDisplayField: string;
      FKeyField: string;
      FPreviousKeyValue: string;  // May be any datatype - see below
    ...
    end;

...

implementation

...
  // Remember previous value
  FPreviousKeyValue:= load_from_settings_in_your_preferred_way_;

...
  // Configure DBLookupCombo
  dsSource.Dataset := dsetSource;
  cboLookup.ListSource := dsSource;

  cboLookup.ScrollListDataset := True;   // This ensures that changing the ComboBox will automatically scroll
                                         // the dataset
  cboLookup.Style := csDropDownList;

  cboLookup.KeyField := FKeyField;       
  cboLookup.ListField := FDisplayField;  // This is the field that will appear in the contents of the ComboBox
  
  dsetSource.Open;  // The ComboBox should now be populated, however intially no text is displayed
                    // So right now there is no relationship between the selected record in the dataset
                    // and the contents of the ComboBox

  // cboLookup.KeyValue reads and writes a Variant, so you may actually define
  // FPreviousKeyValue as any data type you feel is appropriate.

  // Remember a previous value
  if FPreviousKeyValue <> '' then
  begin
    dsetSource.Locate(FKeyField, FPreviousKeyValue, []);  // Note: This will fail to correctly set the ComboBox, 
                                                          // But will set the Datatset to the correct record.
 
    // Now the dataset is on the correct record, lets ensure the DBLookupCombo
    // is showing the same value as the selected record
    If (cboLookup.KeyValue = Null) And (dsetSource.RecordCount > 0) Then
      cboLookup.KeyValue := dsetSource.FieldByName(FKeyField).AsVariant;
  end;

... 
  // Save current value for next time
  FPreviousKeyValue:= cboLookup.KeyValue;
  write_to_settings_in_your_preferred_way_(FPreviousValue);

Bugs

Au moins pour TDBLookupComboBox, il y a un bug avec FPC 2.6.0 (utilisé dans Lazarus 1.0, 1.0.2 etc) qui nécessite que la listfield aussi bien que la DataSource soit présents.

Solution de contournement : vous pouvez passez outre ceci en déclarant un champ calculé avec le même nom que la ListField dans la DataSource du DataSet qui ne fait rien.

Contrôle alternatif

Les contrôles Rx (dans le paquet RxNew) ont le RxDBLookupCombobox qui dispose de fonctionnalités supplémentaires ; il permet p.ex. d'afficher de multiples champs/colonnes à côté l'un de l'autre (un peu comme les ComboBox MS Access) :

RxDBLookupCombo.LookupDisplay = 'field1;field2'; //takes a semicolon-delimited list of fields

Il a en plus une propriété DisplayAllFields (soit afficher tous les champs).

Voir aussi


Composant LCL
Onglet de palette Composants
Standard TMainMenu • TPopupMenu • TButton • TLabel • TEdit • TMemo • TToggleBox • TCheckBox • TRadioButton • TListBox • TComboBox • TScrollBar • TGroupBox • TRadioGroup • TCheckGroup • TPanel • TFrame • TActionList
Additional TBitBtn • TSpeedButton • TStaticText • TImage • TShape • TBevel • TPaintBox • TNotebook • TLabeledEdit • TSplitter • TTrayIcon • TControlBar • TFlowPanel • TMaskEdit • TCheckListBox • TScrollBox • TApplicationProperties • TStringGrid • TDrawGrid • TPairSplitter • TColorBox • TColorListBox • TValueListEditor
Common Controls TTrackBar • TProgressBar • TTreeView • TListView • TStatusBar • TToolBar • TCoolBar • TUpDown • TPageControl • TTabControl • THeaderControl • TImageList • TPopupNotifier • TDateTimePicker
Dialogs TOpenDialog • TSaveDialog • TSelectDirectoryDialog • TColorDialog • TFontDialog • TFindDialog • TReplaceDialog • TOpenPictureDialog • TSavePictureDialog • TCalendarDialog • TCalculatorDialog • TPrinterSetupDialog • TPrintDialog • TPageSetupDialog • TTaskDialog
Data Controls TDBNavigator • TDBText • TDBEdit • TDBMemo • TDBImage • TDBListBox • TDBLookupListBox • TDBComboBox • TDBLookupComboBox • TDBCheckBox • TDBRadioGroup • TDBCalendar • TDBGroupBox • TDBGrid • TDBDateTimePicker
Data Access TDataSource • TBufDataset • TMemDataset • TSdfDataSet • TFixedFormatDataSet • TDbf
System TTimer • TIdleTimer • TLazComponentQueue • THTMLHelpDatabase • THTMLBrowserHelpViewer • TAsyncProcess • TProcessUTF8 • TProcess • TSimpleIPCClient • TSimpleIPCServer • TXMLConfig • TEventLog • TServiceManager • TCHMHelpDatabase • TLHelpConnector
Misc TColorButton • TSpinEdit • TFloatSpinEdit • TArrow • TCalendar • TEditButton • TFileNameEdit • TDirectoryEdit • TDateEdit • TTimeEdit • TCalcEdit • TFileListBox • TFilterComboBox • TComboBoxEx • TCheckComboBox • TButtonPanel • TShellTreeView • TShellListView • TXMLPropStorage • TINIPropStorage • TIDEDialogLayoutStorage • TMRUManager • TStrHolder
LazControls TCheckBoxThemed • TDividerBevel • TExtendedNotebook • TListFilterEdit • TListViewFilterEdit • TTreeFilterEdit • TShortPathEdit • TLvlGraphControl
RTTI TTIEdit • TTIComboBox • TTIButton • TTICheckBox • TTILabel • TTIGroupBox • TTIRadioGroup • TTICheckGroup • TTICheckListBox • TTIListBox • TTIMemo • TTICalendar • TTIImage • TTIFloatSpinEdit • TTISpinEdit • TTITrackBar • TTIProgressBar • TTIMaskEdit • TTIColorButton • TMultiPropertyLink • TTIPropertyGrid • TTIGrid
SQLdb TSQLQuery • TSQLTransaction • TSQLScript • TSQLConnector • TMSSQLConnection • TSybaseConnection • TPQConnection • TPQTEventMonitor • TOracleConnection • TODBCConnection • TMySQL40Connection • TMySQL41Connection • TMySQL50Connection • TMySQL51Connection • TMySQL55Connection • TMySQL56Connection • TSQLite3Connection • TIBConnection • TFBAdmin • TFBEventMonitor • TSQLDBLibraryLoader
Pascal Script TPSScript • TPSScriptDebugger • TPSDllPlugin • TPSImport_Classes • TPSImport_DateUtils • TPSImport_ComObj • TPSImport_DB • TPSImport_Forms • TPSImport_Controls • TPSImport_StdCtrls • TPSCustomPlugin
SynEdit TSynEdit • TSynCompletion • TSynAutoComplete • TSynMacroRecorder • TSynExporterHTML • TSynPluginSyncroEdit • TSynPasSyn • TSynFreePascalSyn • TSynCppSyn • TSynJavaSyn • TSynPerlSyn • TSynHTMLSyn • TSynXMLSyn • TSynLFMSyn • TSynDiffSyn • TSynUNIXShellScriptSyn • TSynCssSyn • TSynPHPSyn • TSynTeXSyn • TSynSQLSyn • TSynPythonSyn • TSynVBSyn • TSynAnySyn • TSynMultiSyn • TSynBatSyn • TSynIniSyn • TSynPoSyn
Chart TChart • TListChartSource • TRandomChartSource • TUserDefinedChartSource • TCalculatedChartSource • TDbChartSource • TChartToolset • TChartAxisTransformations • TChartStyles • TChartLegendPanel • TChartNavScrollBar • TChartNavPanel • TIntervalChartSource • TDateTimeIntervalChartSource • TChartListBox • TChartExtentLink • TChartImageList
IPro TIpFileDataProvider • TIpHttpDataProvider • TIpHtmlPanel