Delphi checklistbox array

1.6k Views Asked by At

I want to change binary code, to checklistbox. When 1 then checklistbox.checked = true, and 0 then checklistbox.checked = false. I have 5 items in checklistbox. when Tedit fill with 11111 and 00000 it work perfectly. But, when I put 11011, fourth item uncheck, not third item.

here is my code,

    procedure TForm1.BUT_2Click(Sender: TObject);
var
i,j, k: Integer;
  kode: array[0..6] of string;
//  checkbox: array[1..5] of TCheckListBox;
begin

  i:=0;
  j:= 1;

  kode[i]:= '0';
  CheckListBOX2.Checked[i]:= True;

  for i:=0 to Length(EDI_2.Text)-1 do
  begin
    kode[i]:= Copy(EDI_2.Text, i, j);
    if kode[i]= '1' then
    begin
      CheckListBOX2.Checked[i]:= True;
    end
    else
    begin
      kode[i]:= Copy(EDI_2.Text, i, j);
      CheckListBOX2.Checked[i]:= False;
    end;

  end;
end;

thank you very much.

1

There are 1 best solutions below

5
On

It's a little hard to work out what you are doing as we only have a partial explanation, and limited code. However, this looks wrong:

Copy(EDI_2.Text, i, j);

Assuming you have 1-based strings (i.e. are not using the mobile compilers) then the loop variable i starts at 0. You should instead use:

Copy(EDI_2.Text, i+1, j);

Now, you don't need j since it is always 1. So it becomes:

Copy(EDI_2.Text, i+1, 1);

And at this point you can remove Copy and use straight character indexing:

EDI_2.Text[i+1]

Note also that it is pointless to assign the same value to kode[i] twice. So the loop could become:

for i := 0 to Length(EDI_2.Text)-1 do
begin
  kode[i] := EDI_2.Text[i+1];
  CheckListBOX2.Checked[i] := (kode[i] = '1');
end;

And now we can see that there is no need for the array kode. So we could just write:

for i := 0 to Length(EDI_2.Text)-1 do
begin
  CheckListBOX2.Checked[i] := (EDI_2.Text[i+1] = '1');
end;

And then we can see that all the code before the loop is pointless. So the entire function would become:

procedure TForm1.BUT_2Click(Sender: TObject);
var
  i: Integer;
  Text: string;
begin
  Text := EDI_2.Text;
  for i := 0 to Length(Text)-1 do
  begin
    CheckListBOX2.Checked[i] := (Text[i+1] = '1');
  end;
end;

And one final point concerning user input data sanitization. If the user has the freedom to put whatever they like in the edit box then they might well provide a string that is either too short or too long. In either case, the code above will not handle that condition. Similarly, if they enter a digit other than 0 or 1 then your code will not object. You need to decide on how to handle these conditions and code accordingly.