Steve88
Steve88

Reputation: 2416

From checklistbox to tcxchecklistbox (save states to TMemoryStream)

Anyone can help how can I transform this to work with tcxchecklistbox?

My Save procedure looks like...

  procedure Tfrm_A.SaveCheckListBoxData(S: TMemoryStream;
  CheckListBox: TCheckListBox);
  var
    i: longint;
    b: boolean;
    buf : string;
  begin
    S.Clear;
    buf := CheckListBox.Items.Text;
    i := Length(buf);

    S.Write(i, SizeOf(i));
    if i > 0 then begin
    S.Write(buf[1], i);

   for i:= 0 to Pred(CheckListBox.Items.Count) do
   begin
     b:= CheckListBox.Checked[i];
     s.Write(b,1);
   end;
  end;
 end;

My load procedure looks like...

procedure Tfrm_A.LoadCheckListBoxData(S: TMemoryStream;
CheckListBox: TChecklistBox);
var
  i: longint;
  b: Boolean;
  buf : string;
begin
  S.Position := 0;
  S.Read(i, SizeOf(i));

  if i > 0 then begin
    SetLength(buf, i);
  S.Read(buf[1], i);
  CheckListBox.Items.Text := buf;

 for i:= 0 to Pred(CheckListBox.Items.Count) do
 begin
   s.Read(b,1);
   CheckListBox.Checked[i] := b;
  end;
 end;
end;

My problem is

buf := CheckListBox.Items.Text; 

TcxChecklistbox has checklistbox.items[Index].textproperty

Thanks for the help!

Upvotes: 1

Views: 510

Answers (1)

MartynA
MartynA

Reputation: 30715

You can use a TStringStream to do this. Basically, it's just a question of iterating the cxCheckBoxList Items and writing a character to the StringStream indicating whether the checkbox is checked, and then reading the stream back a character at a time.

function StateToString(Checked : Boolean) : String;
begin
  if Checked then
    Result := '+'
  else
    Result := '-';
end;

procedure TForm1.SaveStatesToStream(SS : TStringStream);
var
  i : integer;
begin
  SS.Clear;
  SS.Position := 0;
  for i := 0 to cxCheckListBox1.Items.Count - 1 do begin
    SS.WriteString(StateToString(cxCheckListBox1.Items[i].Checked));
  end;
  Memo1.Lines.Add('>' + SS.DataString + '<');
end;

procedure TForm1.LoadStatesFromStream(SS : TStringStream);
var
  i : integer;
  S : String;
begin
  CheckBoxList.ClearCheckmarks;
  SS.Position := 0;
  i := 0;
  while (i <= cxCheckListBox1.Items.Count - 1) and (SS.Position < SS.Size) do begin
    S := SS.ReadString(1);
    cxCheckListBox1.Items[i].Checked := S = '+';
    Inc(i);
  end;
end;

Tested in Delphi Seattle

Upvotes: 1

Related Questions