Link to home
Start Free TrialLog in
Avatar of Cilician
Cilician

asked on

Saving treeview state

Is there any way to save the state of the ttreeview, by that I mean the collapsed/expanded state of a ttreeview's node(s) with subitems? Save it onclose of the form, and load it onactivate.
Thanks.
Avatar of SteveBay
SteveBay
Flag of United States of America image

There is not a direct and easy way to do this. You would need to make a list of expended nodes and store that list upon close and load that list upon startup. The list could be stored in the registry or an ini or a DB.
ASKER CERTIFIED SOLUTION
Avatar of Lukasz Zielinski
Lukasz Zielinski
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Cilician
Cilician

ASKER

Great. Thanks.
this should be better:

uses Math;

procedure SaveTreeState(ATreeView: TTreeView;const AFileName: string);
var cnt: Integer;
    buff: array of Boolean;
    fs: TFileStream;
begin
  if Assigned(ATreeView) and (ATreeView.Items.Count > 0) then begin
    SetLength(buff, ATreeView.Items.Count);
    for cnt := 0 to ATreeView.Items.Count - 1 do
      buff[cnt] := ATreeView.Items[cnt].Expanded;
    fs := TFileStream.Create(AFileName, fmCreate or fmOpenWrite);
    try
      fs.Write(buff[0], ATreeView.Items.Count);
    finally
      fs.Free;
    end;
  end;
end;

procedure LoadTreeState(ATreeView: TTreeView;const AFileName: string);
var cnt: Integer;
    buff: array of Boolean;
    fs: TFileStream;
begin
  if Assigned(ATreeView) then begin
    fs := TFileStream.Create(AFileName, fmOpenRead);
    try
      SetLength(buff, fs.Size);
      fs.Read(buff[0], fs.Size);
      for cnt := 0 to Min(fs.Size, ATreeView.Items.Count) - 1 do
        if buff[cnt] then
          ATreeView.Items[cnt].Expand(False)
        else
          ATreeView.Items[cnt].Collapse(False);
    finally
      fs.Free;
    end;
  end;
end;

ziolko.
one more improvement:

procedure LoadTreeState(ATreeView: TTreeView;const AFileName: string);
var cnt: Integer;
    buff: array of Boolean;
    fs: TFileStream;
begin
  if Assigned(ATreeView) then begin
    fs := TFileStream.Create(AFileName, fmOpenRead);
    try
      if fs.Size > 0 then begin
        SetLength(buff, fs.Size);
        fs.Read(buff[0], fs.Size);
        for cnt := 0 to Min(fs.Size, ATreeView.Items.Count) - 1 do
          if buff[cnt] then
            ATreeView.Items[cnt].Expand(False)
          else
            ATreeView.Items[cnt].Collapse(False);
      end;
    finally
      fs.Free;
    end;
  end;
end;

ziolko.