Mirror

Function to Populate a column of the DBGrid PickList so as to facilitate easy data entry in a grid (Views: 707)


Problem/Question/Abstract:

A function to populate the DBGrid PickList to have auto selection of added field value when the grid is used to display a table

Answer:

The PickList of a DBGrid can be made useful for data entry through a dbgrid. This can be accomplished by the following function.Whenever a new entry is added to a particular field, that too can be made to appear in the picklist with the function given below.The PopulatePickList function can be called within DataSource.OnDataChange event so that it gets updated whenever a new entry is added.

procedure PopulatePickList(Column: TColumn; Table: TTable; FieldName: string);
var
  QryTemp: TQuery;
  i: integer;
begin
  Column.PickList.Clear;
  QryTemp := TQuery.Create(nil);
  with QryTemp do
  begin
    DatabaseName := Table.DatabaseName;
    SQL.Clear;
    SQL.Add('SELECT DISTINCT ' + FieldName + ' from ' + Table.TableName);
  end;

  with QryTemp do
  begin
    Active := True;
    First;
    for i := 0 to QryTemp.RecordCount - 1 do
    begin
      if FieldByName(FieldName).AsString <> '' then
        Column.PickList.Add(FieldByName(FieldName).AsString);
      Next;
    end;
    Active := False;
  end;
  QryTemp.Free;
end;

procedure TForm1.DataSourceDataChange(Sender: TObject; Field: TField);
begin
  PopulatePickList(DBGrid.Columns[2], Table, 'Field');
  //replace table with your tableName of the grid
  //DBGrid.Columns[2] with your DBGrid Column that you want the PickList for
  //Field with the field for the PickList
end;

<< Back to main page