Mirror

TCheckListBox LoadFromFile/SaveToFile Method, included checked state? (Views: 100)


Problem/Question/Abstract:

What to use the TCheckListBox LoadFromFile and SaveToFile Method, and store the checked state at the same time?

Answer:

If you embed the Checked property into the actual entry as a “1” or “0” charter you can save the file with the normal SaveToFile method. When a file is loaded using the LoadFromFile method as normal.  Then extract the first charter from the entry and you will have the checked state.

{====================================}

procedure TFrameRuleEngine.SaveRules;
{====================================}
var
  i: Integer;

begin
  i := 0;
  while i < CheckListBoxRule.Items.Count do
  begin
    if CheckListBoxRule.Items[i] = '' then
    begin
      // Delete entry it is empty
      CheckListBoxRule.Items.Delete(i);
    end
    else
    begin
      // Add a 1 or 0 as the first charter in the entry for checked or not checked
      CheckListBoxRule.Items[i] := IntToStr(Integer(CheckListBoxRule.Checked[i])) +
        CheckListBoxRule.Items[i];
      Inc(i);
    end;
  end;
  // Save the full list as normal
  CheckListBoxRule.Items.SaveToFile(ExtractFilePath(Application.ExeName) +
    'Rule.Txt');
end;

{===================================}

procedure TFrameRuleEngine.LoadRules;
{===================================}
var
  sChecked: string;
  i: Integer;

begin
  if FileExists(ExtractFilePath(Application.ExeName) + 'Rule.Txt') then
  begin
    // Read the file as normal
    CheckListBoxRule.Items.LoadFromFile(ExtractFilePath(Application.ExeName) +
      'Rule.Txt');
    i := 0;
    while i < CheckListBoxRule.Items.Count do
    begin
      if CheckListBoxRule.Items[i] = '' then
      begin
        // Delete an empty entry
        CheckListBoxRule.Items.Delete(i);
      end
      else
      begin
        // Get the checked state
        sChecked := Copy(CheckListBoxRule.Items[i], 1, 1);
        CheckListBoxRule.Items[i] := Copy(CheckListBoxRule.Items[i], 2,
          Length(CheckListBoxRule.Items[i]));
        // Update the Checked property
        CheckListBoxRule.Checked[i] := Boolean(StrToInt(sChecked));
        Inc(i);
      end;
    end;
  end;
end;

<< Back to main page