我想實現一個可排序的DBgrid(當點擊列標題時對它的行進行排序)。我設法按升序排序,但我無法按降序排列。這裏是我設計的設置:可排序的DBGrid
Query1.DatabaseName:='Test';
DataSetProvider1.DataSet:=Query1;
ClientDataSet1.ProviderName:=DataSetProvider1;
DataSource1.DataSet:=ClientDataSet1;
DBGrid1.DatSource:=DataSource1;
,這裏是我的代碼片段:
procedure TForm2.FormShow(Sender: TObject);
begin
Query1.Open;
ClientDataSet1.Data:=DataSetProvider1.Data;
ClientDataSet1.AddIndex('objnameDESC','objname',[ixDescending]);
ClientDataSet1.AddIndex('SUM(cd.worktime)DESC','SUM(cd.worktime)',[ixDescending]);
end;
procedure TForm2.DBGrid1TitleClick(Column: TColumn);
begin
case Column.Index of
0: if ClientDataSet1.IndexFieldNames='objname' then
ClientDataSet1.IndexFieldNames:='objnameDESC'
else
ClientDataSet1.IndexFieldNames:='objname';
1: if ClientDataSet1.IndexFieldNames='SUM(cd.worktime)' then
ClientDataSet1.IndexFieldNames:='SUM(cd.worktime)DESC'
else
ClientDataSet1.IndexFieldNames:='SUM(cd.worktime)';
end;
end;
當我在列標題,單擊第一次排序是按升序進行 - 這樣了到這裏一切都好。當我點擊第二次我希望以降序排序做,而是我得到的消息:
Project ... raised Exception class EDatabaseError with message
'ClientDataSet1: Field 'objnameDESC' not found'.
什麼我做錯了任何想法?
我們的軟件通過每次使用不同'order by'子句重新執行查詢來完成該操作。 –
As @UweRaabe已經指出:不要對'Grid'排序,排序'DataSet',特別是如果它已經是'TClientDataSet'。 –