t e m p o r a l 
 d o o r w a y 

Getting a TDBLookupCombo to show a default value

 

The application is a simple order / product lookup. The problem is getting a TDBLookupCombo to show a default value when a row is encountered that contains no product ID.

These are the components established on a form:

object LookupCombo: TDBLookupComboBox
   Left = 16
   Top = 8
   Width = 145
   Height = 24
   DataField = 'PRODUCT_ID'
   DataSource = TestDatabase.Source
   KeyField = 'ID'
   ListField = 'NAME'
   ListSource = TestDatabase.LookupSource
   TabOrder = 0
end
object DBGrid1: TDBGrid
   Left = 16
   Top = 40
   Width = 401
   Height = 217
   DataSource = TestDatabase.Source
   TabOrder = 1
   TitleFont.Charset = DEFAULT_CHARSET
   TitleFont.Color = clWindowText
   TitleFont.Height = -13
   TitleFont.Name = 'MS Sans Serif'
   TitleFont.Style = []
end

Here are the components in the datasource (TestDatabase):

object Table: TTable
   Active = True
   DatabaseName = 'TestAlias'
   TableName = 'order.DBF'
   Left = 32
   Top = 16
end
object Source: TDataSource
   DataSet = Table
   Left = 120
   Top = 16
end
object LookupTable: TTable
   Active = True
   DatabaseName = 'TestAlias'
   TableName = 'product.DBF'
   Left = 32
   Top = 80
end
object LookupSource: TDataSource
   DataSet = LookupTable
   Left = 120
   Top = 80
end

With this arrangement, as you move the cursor through the grid, the DBLookupCombo shows the values in the grid. The problem comes when you have a record that has no value in that field. In that case, the combo shows no value. For that situation, we have to use the OnDataChange method of the TDataSource.

void __fastcall TTestDatabase::SourceDataChange(TObject *Sender, TField
*Field)
{
   Source->OnDataChange = NULL;

   if (Table->FieldByName("PRODUCT_ID")->IsNull)
   {
      Table->Edit();
      Table->FieldByName("PRODUCT_ID")->AsInteger = 0; // That's my default
      Table->Post();
   };

   Source->OnDataChange = SourceDataChange;
}

Note that you have to disable the event handler with the "Source->OnDataChange = NULL;" and reenable it with "Source->OnDataChange = SourceDataChange;" or you get an EDatabaseError.

Changing the value in the source table forces the combo to the default value.

Of course, you could get more complex by using a table to determine the default value, or whatever.

Note, however, that this causes a permanent change to any record that gets visited.

Copyright © 2004 by Mark Cashman (unless otherwise indicated), All Rights Reserved