cxGrid控件过滤排序和TClientDataSet同步

1.过滤同步

procedure TReport10Form.cxGridViewDataControllerFilterChanged(Sender: TObject);
var
  cds: TClientDataSet;
begin
  cds := cxGridView.DataController.DataSource.DataSet as TClientDataSet;
  try
    cds.Filtered := false;
    cds.Filter := cxGridView.DataController.filter.filtertext;
    cds.Filtered := True;
  except
    cds.Filter:='';
  end;
end;

2.排序同步

procedure TaxisDataSet(Column: TColumnEh; var aDataSet: TClientDataSet);
var
  IndexDataSet: ^TClientDataSet;
  IsDesc: boolean;
begin
  IndexDataSet := @aDataSet;
//  if LastColumn <> nil then     //中文长度为2
//    LastColumn.Title.Caption := Copy(LastColumn.Title.Caption, 1, Length(LastColumn.Title.Caption) - 2);

//  LastColumn := Column;
  if (IndexDataSet.IndexDefs.Count > 0) and (IndexDataSet.IndexDefs[0].Fields = Column.FieldName) then
  begin
    if IndexDataSet.IndexDefs[0].Options = [ixDescending] then
      IsDesc := false
    else
      IsDesc := true;
  end
  else
  begin
    IsDesc := false;
  end;

  IndexDataSet.DisableControls();
//  self.cdsVMember.IndexFieldNames := Column.FieldName;

  IndexDataSet.IndexDefs.Clear();
  with IndexDataSet.IndexDefs.AddIndexDef do
  begin
    Fields := Column.FieldName;
    if IsDesc then
    begin                             //12.8.206 lero
      Name := 'DescIndex' + 'Tmp';  //'tmp'代替 Column.FieldName 避免Name长度过长 引起错误
      Options := [ixDescending];
//      Column.Title.Caption := Column.Title.Caption + '↓';  //
    end
    else
    begin
      Name := 'Index' + 'Tmp';
//      Column.Title.Caption := Column.Title.Caption + '↑'; //
    end;
  end;
  IndexDataSet.IndexName := IndexDataSet.IndexDefs.Items[0].Name;
  IndexDataSet.EnableControls();
end;

3.动态的显示数据源数据

var Tableview:TcxGridDBTableView; //定义

......

TableView := TcxGridDBTableView(cxGrid1.CreateView(TcxGridDBTableView));
with TableView do
begin
DataController.DataSource := datasource2; // 确定数据源
self.cxGrid1Level1.GridView:= TableView; //绑定视图
(DataController as IcxCustomGridDataController).DeleteAllItems; //删除所有列
(DataController as IcxCustomGridDataController).CreateAllItems(false);//创建数据源中的所有列
end;
for i:=0 to tableview.ColumnCount-1 do
begin
//判断数据视图中是否包含产品两字的列,以便加长宽度显示
if AnsiContainsText(tableview.Columns.DataBinding.FieldName,'产品')=true then
begin
tableview.Columns.Width:=120 ;
end else
begin
tableview.Columns.Width:=50 ;
end;
end;

原文地址:https://www.cnblogs.com/false/p/2924240.html