Dear ALL,
I have a dialog with a CheckListBox and want to build a string with the numbers of the items selected by the user, for example:
[X] Item 1
[ ] Item 2
[X] Item 3
[ ] Item 4
[ ] Item 5
This is obviously quite simple to achive with some code as follows:
for J := 0 to CheckListBox1.Count - 1 do
if CheckListBox1.Checked[J] then
ResultStr := IntToStr(J + 1) + ' ';
and the result string will be: '1 3';
However, if the user select a sequence of contiguous items, I want that the result string be returned as a 'range' giving only the first and last numbers in the sequence. For example, suppose the user selects the first three items in the sequence:
[X] Item 1
[X] Item 2
[X] Item 3
[ ] Item 4
[ ] Item 5
To build the range, I store the numbers of the selected items in a StringList and modify the above code accordingly:
S := TStringList.Create;
for J := 0 to CheckListBox1.Count - 1 do
begin
if CheckListBox1.Checked[J] then
S.Add(IntToStr(J + 1));
end;
if S.Count = 1 then
ResultStr := S[0]
else if S.Count > 1 then
ResultStr := S[0] + '-' + S[S.Count - 1]
else
ResultStr := '';
S.Free;
In this case, the result string will be: '1-3';
So far, so good. But my problem (yes, I finally got to it!) is how to build the result string when the user selects
non-contiguous items in the CheckListBox, for example:
[X] Item 1
[X] Item 2
[X] Item 3
[ ] Item 4
[X] Item 5
The result string should be a range ('1-3') plus a single number string ('5'), as follows: '1-3 5'.
My problem is therefore that of identifying if the items the user has selected are contiguous or non-contiguous. Any ideas on how to achieve this?
I attach may test source code.
Thanks in advance for any assistance you can provide.
With
best wishes,