how to set a default value for a column in cxGrid?

1.9k Views Asked by At

How to set a default value for a boolean column in cxGrid? I mean i would like that by default all new rows have the value "False" for my boolean column

1

There are 1 best solutions below

4
On BEST ANSWER

Assuming this is a data grid (containing e.g. a cxGridDBTableView), you should set any defaults in the dataset's OnNewRecord event, like this

procedure TForm1.ClientDataSet1NewRecord(DataSet: TDataSet);
var
  Field : TField;
  i : Integer;
begin
  // set all Boolean data fields to False
  for i := 0 to DataSet.FieldCount - 1 do begin
    Field := DataSet.Fields[i];
    if (Field.DataType = ftBoolean) and (Field.FieldKind = fkData) then
    // the test on Field.FieldKind is to avoid disturbing any fkCalculated or fkInternalCalc fields
      Field.AsBoolean := False;
  end;
end;

If you do that (or set any other field values in the OnNewRecord event), the values will automatically be transferred to the cxGrid.

Update The following shows how to set an initial False value for a boolean column of an unbound cxGridTableView. Note: The code creates the TableView so there is no need to add it or a cxGrid to the form.

    // form fields (of Form1)
    cxGrid1 : TcxGrid;
    cxLevel : TcxGridLevel;
    TableView : TcxGridTableView;
    Col1,
    Col2,
    Col3 : TcxGridColumn;
  end;

 [...]
procedure TForm1.FormCreate(Sender: TObject);
begin
  cxGrid1 := TcxGrid.Create(Self);
  cxGrid1.Parent := Self;

  cxLevel := cxGrid1.Levels.Add;
  cxLevel.Name := 'Firstlevel';

  TableView := TcxGridTableView.Create(Self);
  TableView := cxGrid1.CreateView(TcxGridTableView) as TcxGridTableView;
  TableView.Name := 'ATableView';
  TableView.Navigator.Visible := True;

  Col1 := TableView.CreateColumn;
  Col1.DataBinding.ValueType := 'Integer';
  Col1.Caption := 'RowID';

  Col2 := TableView.CreateColumn;
  Col2.DataBinding.ValueType := 'String';
  Col2.Caption := 'RowName';

  Col3 := TableView.CreateColumn;
  Col3.DataBinding.ValueType := 'Boolean';
  Col3.Caption := 'RowChecked';

  cxLevel.GridView := TableView;

  TableView.DataController.OnNewRecord := cxGridTableViewDataControllerNewRecord;
end;

procedure TForm1.cxGridTableViewDataControllerNewRecord(
  ADataController: TcxCustomDataController; ARecordIndex: Integer);
begin
 Caption := IntToStr(ARecordIndex);
  ADataController.Values[ARecordIndex, 2] := False;  // The 2 is the index of Col3
end;