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.
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:
Assuming you have 1-based strings (i.e. are not using the mobile compilers) then the loop variable
i
starts at0
. You should instead use:Now, you don't need
j
since it is always1
. So it becomes:And at this point you can remove
Copy
and use straight character indexing:Note also that it is pointless to assign the same value to
kode[i]
twice. So the loop could become:And now we can see that there is no need for the array
kode
. So we could just write:And then we can see that all the code before the loop is pointless. So the entire function would become:
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
or1
then your code will not object. You need to decide on how to handle these conditions and code accordingly.