【问题标题】:how to set a default value for a column in cxGrid?如何为 cxGrid 中的列设置默认值?
【发布时间】:2020-02-22 16:16:36
【问题描述】:

如何为 cxGrid 中的布尔列设置默认值?我的意思是我希望默认情况下所有新行的布尔列的值为“False”

【问题讨论】:

  • 假设您正在显示来自数据集的数据,执行此操作的方法是在数据集的 OnNewRecord 事件中将相应数据字段的值设置为 False。顺便说一句,很遗憾你删除了 ShowEndEllipsis q - 有趣且相当具有挑战性(对我而言)q。
  • @MartynA 哦,对不起 ShowEndEllipsis 问题:( 我找到了解决方案,只是将 OptionBehavior.CellHints 设置为 true,我想我的问题很快就会被否决,这就是我删除它的原因:( 抱歉下次我不会再删了!
  • 别担心 ShowEndEllipsis q,我很高兴你解决了它。我完全知道你所说的反对票是什么意思!

标签: delphi devexpress devexpress-windows-ui tcxgrid quantumgrid


【解决方案1】:

假设这是一个数据网格(例如包含 cxGridDBTableView),您应该在数据集的 OnNewRecord 事件中设置任何默认值,如下所示

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;

如果您这样做(或在 OnNewRecord 事件中设置任何其他字段值),这些值将自动传输到 cxGrid。

更新 下面展示了如何为一个布尔值列设置一个初始的 False 值 未绑定的 cxGridTableView。注意:代码创建了 TableView 所以不需要 将它或 cxGrid 添加到表单中。

    // 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;

【讨论】:

  • 感谢 Martyn,实际上它不是 DBTableView 而只是 tableView。我希望我的所有布尔列默认都有一个错误值而不是一个空(灰色)值
  • 查看更新以了解如何处理普通的 cxGridTableView。
  • 嗯,您可能会猜到我不太熟悉使用未绑定的网格,您会注意到代码总是在 TableView 的顶部添加新行。接下来我需要做的是弄清楚如何在末尾添加新行(或按照其他顺序)。
  • 它非常适合我,cxGridTableViewDataControllerNewRecord 为我指明了正确的方向,现在可以正常工作了 :)
猜你喜欢
  • 1970-01-01
  • 2015-10-10
  • 2011-10-11
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2016-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多