Well, I thought I would be clever and simply reuse the two initial indexes as they are the only ones that are in indexdefs, but that does not work either even though I change the fieldnames to the current column, it seems to always be holding on the first ones added.
It seems there is a pointer issue with indexdefs, the list is not holding the correct pointer to the actual index:
procedure TSQLForm.ResultsGridTitleClick(Column: TColumn);
var
ASC_IndexName,DESC_IndexName:string;
x:integer;
aindex:TIndexDef;
begin
ASC_IndexName:='ASC_';
DESC_IndexName:='DESC_';
//indexes cant sort binary types such as ftmemo, should add blob types to this as well
if(Column.Field.DataType = ftmemo) or (Column.Field.DataType = ftwidememo)then Exit;
//check if a Ascending index already exists for this column, if not create one
x:=OpenQuery.IndexDefs.IndexOf(ASC_IndexName);
if x = -1 then
openquery.AddIndex(ASC_IndexName,column.FieldName,[]) else
begin
aindex:= openquery.IndexDefs.Items[x];
aindex.Fields:=column.FieldName;
end;
//check if a Descending index already exists for this column, if not create one
x:= OpenQuery.IndexDefs.IndexOf(DESC_IndexName);
if x = -1 then
openquery.AddIndex(DESC_IndexName,column.FieldName,[ixDescending]) else
begin
aindex:= openquery.IndexDefs.Items[x];
aindex.Fields:=column.FieldName;
end;
//ensure index defs are up to date
OpenQuery.IndexDefs.Updated:=false; {<<<<---Won't work without this line}
openquery.IndexDefs.Update;
//use the column tag to toggle ASC/DESC
column.tag := not column.tag;
if boolean(column.tag) then
begin
Column.Title.ImageIndex:=12;
openquery.IndexName:=ASC_IndexName;
end else
begin
Column.Title.ImageIndex:=13;
OpenQuery.IndexName:=DESC_IndexName;
end;
if (flastcolumn <> nil) and (flastcolumn <> Column) then
flastcolumn.Title.ImageIndex:=-1;
flastcolumn:=column;
end;