cxGrid的使用方法

1.  去掉cxgrid中抬头的box ,在tableview1的ptionsview的groupbybox=false;
2.  在GRID footer 中加入sum(列), tableview1的optionsview的footer=ture
然后在cxGRid1的customize中的summary 的footer.add需要合计的列kind= skSum
3.  去掉cxgrid 中的过滤下拉箭头选择tableview1.optionscustomize.columnfiltering=fasle;
4.   cxGrid1DBTableView1 的 OptionView中屬性GroupFooters設為gfAlwaysVisible並設置需要求和的列,在summary.default for Groups 下add加入需要合计的字段,column下显示fieldname 为统计字段,format为格式,kind为统计方法,position 为位子 spfooter 在分组的下面,spgroup 在分组的上面
或用cxGridPopupMenu1,在運行時可對任意數字類型列求和,方法是只需設置cxGridPopupMenu1的屬性Grid為cxGrid1DBTableView1的cxGrid,
即可實現您所需功能
5.  DEV Express里的cxGrid默认的数值格式带¥,怎么去掉啊!
   雙擊Cxgrid,選擇colmnum改變類型 options.properties.Memo,在displayformat中进行设置
6.  在网格最后一行的最后一格回车自动增加一条记录,并跳到新记录的第一格
设置cxGrid1DBTableView1的OptionsBehavior的FocusFirsCellOnNewRecord与GoToNextCellOnEnter为True,FocusCellOnCycle设为True
7. 网格中通过Tab跳转,设置cxGrid1DBTableView1的OptionsBehavior的FocusCellOnTab为True
8.设置是否能够在网格中编辑数据,设置cxGrid1DBTableView1的OptionsData的Appending设为True,Deleting为True,Editing为True
9.设置是否能选中网格,设置cxGrid1DBTableView1的OptionsSelection的CellSelect为True
10.设置是否能够反选,设置cxGrid1DBTableView1的OptionsSelection的InsertSelect为True
11.设置行高:在cxGridDBTableView1.OptionsView.DataRowHeight
12.改变字体在
  cxStyleRepository 双击它,在里面添加GridTableViewStyleSheetDevExpress
  然后改变Style标签里面的cxStyle的字体就可以控制cxGrid的字体了

13.有图片和MEMO的例子:
    拖入一个cxGrid1,Table1,DataSource1。 Table1的DatabaseName设为DBDEMOS,TableName设为biolife.db,
Active设为True;DataSource1的DataSet设为Table1;cxGrid1DBTableView1的DataController中的DataSource

   设为DataSource1;右击cxGrid1DBTableView1选择Create All Columns;双击cxGrid1,在弹出的窗口中找到  
cxGrid1DBTableView1Notes和cxGrid1DBTableView1Graphic,将它们的Properties属性设为BlobEdit;运行看看结果。再将cxGrid1DBTableView1Graphic的Properties属性设为Image,再将Properties下的Stretch设为True, 将cxGrid1DBTableView1->optionsview->CellAutoHeight 设为True,看看结果。
14.如何让“Drag a column here to group by that column”不显示
    解决:点击cxGrid1上的cxGrid1DBTableView1
    在cxGrid1DBTableView1->optionsview->groupbybox:=false即可
15.GroupPanel上面的英文[Drag a column header to group by that column]怎么可以改成中文?
    解决:最简单的方法是 TcxGridTableView.OnCustomDrawPartBackground ,也可用 OnCustomDrawGroupCell:
    procedure TForm1.cxGrid1DBTableView1CustomDrawPartBackground(
               Sender: TcxGridTableView; ACanvas: TcxCanvas;
              AViewInfo: TcxCustomGridCellViewInfo; var ADone: Boolean);
    begin
      AViewInfo.Text:='动态设置 GroupBox 的显示内容';
      ACanvas.FillRect(AViewInfo.Bounds);
    end;
16.如何实现如下功能:
           +财务部
           +原材料仓库
           +成品库
           +冲压车间
           +软件开发部
    这个是部门的名称,点击加号就可以将本部门的人员情况显示出来。
    解决:其实这是一个主从表关系,
 (1):填好主表的keyfieldnames
    (2):填好从表的keyfieldnames
 (3):填好从表的 detaikeyfieldNames与masterkeyfieldnames
    (4): 从表的数据源一定要按与主表关联的字段排序    注:其它地方设置了主从表结构那样就显示不出来,比如设置了从表的Table或者Query的mastersource和
   asterfield就会不能显示数据!如果是两个cxGrid的主从关系,这样设置就很OK了。
17.类似PageControl显示         解决:增加一个Level,将cxGrid1->RootLevelOptions->DetailTabsPosition设为dtpTop,然后相应的设置cxGrid1Level1,和cxGrid1Level2的Caption值。 
18.如何设定左边几列,不能滚动?
   解决:使用DB Banded Table才可以实现,
         在cxGrid1DBBandedTableView里建立Band0,Band1
         Band0的Fixed=tfLeft
         Band1的Fixed=tfnone
         设置要锁定的字段的BandIndex=0,其它为1,就OK了。
19.怎样实现如EXCEL一样的,当前格=G14+G15+G16 这样的功能
   解决:举一个简单的例子:label1.Caption := cxGrid1DBTableView1.DataController.Values[2,
3]+cxGrid1DBTableView2.DataController.Values[1, 1]+cxGrid1DBTableView3.DataController.Values[1, 1];
所以不同cxGrid1DBTableView中的数据都可以给当前格,这样就做到了EXCEL中的当前格=G14+G15+G16 类似的功能。

20.鼠标右击cxGrid1DBBandedTableView1菜单里的Edit Layout什么用,怎么使用?    解决:可以拖动字段,并列的可以拖成有层次感(一层层),拖动时会显示箭头的,就是说可以拖一个字段放

到最上面,就可以使记录按此字段进行分组。点击其中一个字段,上面还会出现一个上升或者下降的小三角形,这个

小三角形的作用是在运行阶段,数据就会按照这个字段上升或者下降排序。
    还有一个Set as Default的作用是保持当前TableView的参数,下此产生新的TableView的时候就会可以和上次保持的参数一样。这个还没有做过试验。
21.怎样将cxGrid里的数据导入到EXCEL,HTML,XML和TEXT
  解决:这个问题在用了cxGrid以后变得异常简单,
uses
 cxExportGrid4Link;

procedure TForm1.Button1Click(Sender: TObject);
begin
 ExportGrid4ToEXCEL('d:\wang.xsl',cxGrid1,True,True);
 ExportGrid4ToTEXT('d:\wang.txt',cxGrid1,True,True);
 ExportGrid4ToXML('d:\wang.xml',cxGrid1,True,True);
 ExportGrid4ToHTML('d:\wang.html',cxGrid1,True,True);
end;

22.如何使满足条件的数据显示不同的颜色?
解决:
var
AYellowStyle: TcxStyle;

procedure TForm1.FormCreate(Sender: TObject);
begin
  //行颜色
  AYellowStyle := TcxStyle.Create(Self);
  AYellowStyle.Color := $0080FFFF;
  AYellowStyle.TextColor := clMaroon;
end;

procedure TForm1.cxGrid1DBBandedTableView1StylesGetContentStyle(
Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
begin
if ARecord.Values[cxGrid1DBBandedTableView1Lengthcm.Index] < 81 then
  AStyle := AYellowStyle;
end;

这里cxGrid1DBBandedTableView1Lengthcm.Index小于81时就显示黄色

23.如何从外边的TXT文件导入到cxGrid?
解决:    procedure CustomizeColumns;
          procedure LoadData;

procedure TForm1.CustomizeColumns;
const
 cDistance = 1;
 cRadius = 5;
 cPeriod = 4;
 cPstring = 0;
var
 I: Integer;
begin
 DecimalSeparator := '.';
 with cxGrid1TableView2 do
 for I := 0 to ColumnCount - 1 do
   if I in [cDistance, cRadius] then
     Columns[I].DataBinding.ValueTypeClass := TcxIntegerValueType//1,5列为Integer
   else
     if I in [cPstring,cPeriod] then
     Columns[I].DataBinding.ValueTypeClass := TcxStringValueType//0,4列为String
     else
      Columns[I].DataBinding.ValueTypeClass := TcxFloatValueType;//其他为Float
end;

procedure TForm1.LoadData;
const
 AFileName = '资产负债表.txt';
 AHeaderLineCount = 2;

var
 ARecords, AValues: TStringList;
 I: Integer;

 procedure InitRecord(const Str: string);
 var
   J: Integer;
   V: Variant;
 begin
   AValues.CommaText := Str;
   for J := 0 to AValues.Count - 1 do
    if AValues.Strings[J] <> '-' then
    begin
     V := AValues.Strings[J];
     if not VarIsNull(V) then
       cxGrid1TableView2.DataController.Values[I, J] := V;
    end;
 end;

begin
 if not FileExists(AFileName) then
   raise Exception.Create('Data file not found');

 ARecords := TStringList.Create;
 AValues := TStringList.Create;

 with ARecords do
 try
   LoadFromFile(AFileName);
   cxGrid1TableView2.BeginUpdate;
   cxGrid1TableView2.DataController.RecordCount := Count - AHeaderLineCount;
   for I := 0 to Count - (AHeaderLineCount + 1) do
     InitRecord(Strings[I + AHeaderLineCount]);
 finally
   cxGrid1TableView2.EndUpdate;
   ARecords.Free;
   AValues.Free;
 end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
 CustomizeColumns;
 LoadData_Zcfz;
end;

24.如何改变列的颜色?
var
 AFirstColumnStyle: TcxStyle;

procedure TForm1.FormCreate(Sender: TObject);
begin
 //列颜色
 AFirstColumnStyle := TcxStyle.Create(Self);
 AFirstColumnStyle.Color := clAqua;
 AFirstColumnStyle.TextColor := clBlue;
 cxGrid1TableView1.Columns[1].Styles.Content := AFirstColumnStyle;
end;

25.Set as default的用法?
 解决:Set as default的用法是为了解决设置参数的方便而做的,比如:
       连好数据库以后,更改cxGrid1DBBandedTableView1->OptionsCustomize-> ColumnFiltering 设为False。(这个设置可以将字段名的下拉单给去掉)更改cxGrid1DBBandedTableView1->OptionsView- >Navigator 设置为True。然后右击cxGrid1DBBandedTableView1,在弹出的菜单栏里面点击Set as default。
  OK,下次你再产生一个新的cxGrid1DBBandedTableView1时这些设置和刚才的一样了。如果需要设置的参数很多的时候,这个Set as default很有用!
 
26.怎样使鼠标移动时,相应的单元里的文字变色?
  解决:
var
 FTrackItem: TcxCustomGridTableItem;
 FTrackRec: TcxCustomGridRecord;

procedure TForm1.cxGrid1DBTableView1CustomDrawCell(
 Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
 AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
 if (AViewInfo.GridRecord = FTrackRec) and (AViewInfo.Item = FTrackItem) then
 begin
   ACanvas.Font.Color := clred;   //红色字体
   ACanvas.Font.Style := [fsUnderline];//带下划线
 end;
end;

procedure TForm1.cxGrid1DBTableView1MouseMove(Sender: TObject;
 Shift: TShiftState; X, Y: Integer);
var
 AHitTest: TcxCustomGridHitTest;
 ATrackItem: TcxCustomGridTableItem;
 ATrackRec: TcxCustomGridRecord;
begin
 ATrackItem := FTrackItem;
 ATrackRec := FTrackRec;

 AHitTest := (Sender as TcxGridSite).GridView.ViewInfo.GetHitTest(X, Y);
 if AHitTest is TcxGridRecordCellHitTest then
 begin
   FTrackItem := TcxGridRecordCellHitTest(AHitTest).Item;
   FTrackRec := TcxGridRecordCellHitTest(AHitTest).GridRecord;
 end
 else
 begin
   FTrackItem := nil;
   FTrackRec := nil;
 end;

 if (ATrackItem <> FTrackItem) or (ATrackRec <> FTrackRec) then
 begin
   // Invalidate old cell
   if ATrackRec <> nil then
     ATrackRec.Invalidate(ATrackItem);
   // Invalidate new cell
   if FTrackRec <> nil then
     FTrackRec.Invalidate(FTrackItem);
 end;
end;

27.怎样设计多表头的cxGrid?
  解决:cxGrid可以解决如下的表头:
                   ---------------------------------
                   |     说明1     |     说明2     |
                   ---------------------------------
                   | 字段1 | 字段2 | 字段3 | 字段4 |
                   |      字段5    |     字段6     |
                   |      字段7    | 字段8 | 字段9 |
实现这个很简单,你可以直接在上面拖动字段名,拖动时会显示箭头的,放入你想显示的位置就OK了。或者在鼠标右击cxGrid1DBBandedTableView1菜单里的Edit Layout里也可以拖放。

28.在主从表结构时,当点开“+”时怎样将焦点聚在相应主表的记录上?
解决:
var
 HitTest: TcxCustomGridHitTest;

procedure TColumnsShareDemoMainForm.tvProjectsMouseDown(Sender: TObject;
 Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
 // Note that the Sender parameter is a Site
 HitTest := (Sender as TcxGridSite).GridView.ViewInfo.GetHitTest(X, Y);
 // The point belongs to the [+]/[-] button area
 if HitTest is TcxGridExpandButtonHitTest then
   // Move focus to the record
   TcxGridExpandButtonHitTest(HitTest).GridRecord.Focused := True;
end;

29.CXGrid4如何展开全部节点
 解决:GridDBTableView1.DataController.Groups.FullExpand;
 

30.cxGrid如何动态创建Items的Editor的项?
   cxGrid的列有一个属性,它的编辑框可以指定combobox,spinedit等.在设计时,可以为
   combobox的items添加项目.请问是否可以动态创建?(run-time时由程序加入)

  解决:
 var
   A:TDataSource:
   B:TcxlookupcomboboxProperties;
    begin
   A:=TDataSource.create(self);
   B:=tcxlookupcomboboxproperties.create(self);
   A.Dataset:=Dic_ry_xb;//此处指定数据源。
   b.listdource:=a;//此处指明字段的listsource属性。
   b.keyfieldnames:='a';    //此处指明字段的关键字段
   b.listfieldnames:='b';   //此处指明字段的返回值。
   b.listcolumns.items[0].caption:='x;                              //此处默认是会建立一个字段,但是显示的表头是name,所以此处让它显示为自己想要的中午显示。
        cxGrid1DBTableView1c1_sex_code.Properties:=b;  //此处指明是那个字段。
end;  //这个是初始化的代码,

31.获得当前行
   cgBrowseView.DataController.GetSelectionAnchorRowIndex

32.分组
  设置DBTableView的OptionCustomize->ColumnGrouping为True
  并设置要分组的字段的GroupIndex为一大于等于0的值

33.TdxDBTreeView的节点移动排序
利用TdxDBTreeView控件(此处设为DBTreeMain)时,可以从表中直接显示出树结构,有时需要拖动对节点进行排序,而且数据表中有字段SortCode用于排序码,此时需要编写对应代码,步骤如下
(1).先设置DBTreeMain的DragMode属性为dmAutomatic
(2).设置DBTreeMain的StateIndexField属性为SortCode
(3).在其OnEndDragTreeNode事件中写入
var
  m: TNodeAttachMode;
  oldOption: TdxDBTreeViewOptions;
  node: TdxDBTreeNode;
  bm: TBookmarkStr;
  idx: Integer;
begin
  inherited;
  try
    frmDragOption := TfrmDragOption.Create(nil);
    if frmDragOption.ShowModal = mrOK then
    begin
      //ShowMessage('1');
      if frmDragOption.rgOption.ItemIndex = 0 then
        m := naInsert
      else
        m := naAddChild;
      AttachMode := m;
      with DBTreeMain do
      begin
        oldOption := Options;
        Options := Options - [trCanDBNavigate];
        OnCompare := nil;
        bm := qryTree.Bookmark;
        qryTree.DisableControls;
        Items.BeginUpdate;
        try
          if m = naInsert then
          begin
            node := TdxDBTreeNode(Destination);
            idx := node.ImageIndex;
            UpdateSortCode(Source, idx);
            while node <> nil do
            begin
              Inc(idx, 10);
              UpdateSortCode(node, idx);
              node := TdxDBTreeNode(node.getNextSibling);
              if node = Source then
                Break;
            end;
          end
          else //添加子
          begin
            idx := GetChildMaxIdx(Destination) + 10;
            UpdateSortCode(Source, idx);
          end;
        finally
          Items.EndUpdate;
          Options := oldOption;
          OnCompare := DBTreeMainCompare;
          qryTree.EnableControls;
          qryTree.Bookmark := bm;
        end;
      end;
    end
    else
      //
  finally
    frmDragOption.Free;
  end;
end;

//UpdateSortCode过程
procedure TfrmSetTree.UpdateSortCode(ANode: TTreeNode; ASortCode: Integer);
var
  key: Variant;
begin
  key := TdxDBTreeNode(ANode).KeyFieldValue;
  with qryTree do
  begin
    if Locate('ID', key, []) then
    begin
      Edit;
      FieldByName('SortCode').AsInteger := ASortCode;
      Post;
    end;
  end;
  ANode.ImageIndex := ASortCode;
end;

//GetChildMaxIdx过程
function TfrmSetTree.GetChildMaxIdx(ANode: TTreeNode): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := 0 to ANode.Count - 1 do
  begin
    if ANode[i].ImageIndex > Result then
      Result := ANode[i].ImageIndex;
  end;
end;

(4).在其OnCompare事件中写入
procedure TfrmSetTree.DBTreeMainCompare(Sender: TObject; Node1,
  Node2: TTreeNode; Data: Integer; var Compare: Integer);
begin
  inherited;
  if Node1.ImageIndex > Node2.ImageIndex then
    Compare := 1
  else if Node1.ImageIndex = Node2.ImageIndex then
    Compare := 0
  else
    Compare := -1;
end;


34.在TdxDBTreeView控件的OnEditing事件中写入
AllowEdit := CheckEdit;  //CheckEdit为判断的函数

35.选择某一行
cxgrdimport.SetFocus;
DBTVimport.ViewData.Records[0].Selected;

36.cxgrid单击某一网格事件,可在ViewTable的KeyPress事件中判断
if Key = #32 then
begin
  if Trim(colname.EditValue) = '' then
    colcode.FocusWithSelection
  //else
  //  colReqNum.Editing := True;
end;

37.动态生成列
  procedure CreateDynamicCols;
  var
    i, B_index: Integer;
  begin
    with BTVgather.Bands.Add do
    begin
      Caption := lcb1.Text;
      Position.ColIndex := 2;
    end;

    for i := 4 to dsgather.DataSet.FieldCount - 1 do
    begin
      with BTVgather.Bands.Add do
      begin
        Position.BandIndex := 2;
        B_index := Index;
        Caption := dsgather.DataSet.Fields[i].FieldName;
        with BTVgather.CreateColumn do
        begin
          Position.BandIndex := B_index;
          Caption := dsgather.DataSet.Fields[i].FieldName;
          DataBinding.FieldName := dsgather.DataSet.Fields[i].FieldName;
          PropertiesClassName := 'TcxCurrencyEditProperties';
          TcxCurrencyEditProperties(Properties).DisplayFormat := ',0.00;-,0.00';
          Width := 80;
          OnGetDisplayText := Self.OnGetDisplayText;
        end;
      end;
    end;
    if BTVgather.Bands[2].ChildBandCount = 1 then
      BTVgather.Bands[2].Width := 90
    else
      BTVgather.Bands[2].Width := BTVgather.Bands[2].ChildBandCount * 90;
  end;

38.如何判断cxgrid单击了哪一列
procedure TFormModel.cxGrid1DBTableView1CellClick(
  Sender: TcxCustomGridTableView;
  ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
  AShift: TShiftState; var AHandled: Boolean);
begin
  ShowMessage(ACellViewInfo.Item.Caption);
 
  //s :=ACellViewInfo.GridRecord.Values[ACellViewInfo.Item.Index];
  //showmessage(s);
end; 

39.改变CheckBox后直接提交(在PropertiesEditValueChanged中实现)

首先要设置此字段的options->Editing为True,然后写入代码(假设此字段为ViewDataColumn11):
procedure TfrmMain.ViewDataColumn11PropertiesEditValueChanged(
  Sender: TObject);
var
  RecMark:string;
begin
  inherited;
  ViewData.NavigatorButtons.Post.Click;
  if (FBiz.QryData1.FieldByName('PrintFlag').AsInteger=0) and
    (FBiz.QryData1.FieldByName('BillNo').AsInteger=0) then
  begin
    RecMark :=FBiz.QryData1.Bookmark;
    FBiz.QryData1.DisableControls;
    ExecQuery(qryRemote1,'update main set PrintFlag=0 where type='+FBiz.QryData1.FieldByName('Type').AsString);
    ShowQuery(FBiz.QryData1,'select * from Main order by Type,Code,BillNo');
    FBiz.QryData1.EnableControls;
    FBiz.QryData1.Bookmark :=RecMark;
end;
end; 

40.根据数据改变行的颜色

procedure TfrmMain.ViewDataStylesGetContentStyle(
  Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord;
  AItem: TcxCustomGridTableItem; out AStyle: TcxStyle);
begin
  inherited;
  if (ARecord.Values[ViewDataColumn2.Index]=0) and
    (ARecord.Values[ViewDataColumn3.Index]=999999) then
    AStyle :=cxStyle4;
end;

41.动态生成汇总列 

procedure TfrmMain.CreateDynamicCols;
var
  csgItem: TcxDataSummaryItem;
  i: Integer;
begin
{$IFDEF Test}codesite.SendMsg('1'); {$ENDIF}
  btv2.DataController.Summary.FooterSummaryItems.Clear;
  for i := 0 to dsview2.DataSet.FieldCount - 1 do
  begin
    btv2.DataController.Summary.BeginUpdate;

    with btv2.CreateColumn do
    begin
      Caption := dsview2.DataSet.Fields[i].FieldName;
{$IFDEF Test}codesite.SendMsg(Caption); {$ENDIF}
      DataBinding.FieldName := dsview2.DataSet.Fields[i].FieldName;
      HeaderAlignmentHorz := taCenter;

      if i > 0 then
      begin
        PropertiesClassName := 'TcxCurrencyEditProperties';
        if (i mod 2) = 0 then
        begin
          TcxCurrencyEditProperties(Properties).DisplayFormat := ',0.00;-,0.00';
          csgItem := btv2.DataController.Summary.FooterSummaryItems.Add;
          csgItem.ItemLink := BTV2.Columns[i];
          csgItem.Kind := skSum;
          csgItem.Position := spFooter;
        end
        else
          TcxCurrencyEditProperties(Properties).DisplayFormat := ',0;-,0';
      end;
{$IFDEF Test}codesite.SendMsg('2'); {$ENDIF}
      if i > 1 then
        Position.BandIndex := 1;
      if i = 0 then
        Width := 78
      else
        if i = 1 then
          Width := 96
        else
          Width := 84;
    end;
{$IFDEF Test}codesite.SendMsg('3'); {$ENDIF}
    BTV2.Bands[0].Width := 78 + 96;
    BTV2.Bands[1].Width := BTV2.Bands[1].ChildBandCount * 84;
    btv2.DataController.Summary.EndUpdate;
  end;
end;

原文地址:https://www.cnblogs.com/djcsch2001/p/1780573.html