How to delete all children from a TTreeViewItem? - delphi

Is there a way to delete all children from a TTreeViewItem? I tried DeleteChildren but that causes crashes.
What I thought what was a simple question turns out to generate many more questions. That's why I explain of what I am trying to do.
My application tries to generate a directory tree in Delphi XE5 FMX. I use TTreeView for that. It starts by generating a list of drives, all of them TTreeViewItem's owned by TTreeView. When the user clicks on an item the directories below are added to the directory and the TTreeViewItem clicked upon expands. When the user clicks again the TTreeViewItem callapses. This has one caveat: the next time the user clicks on the same TTreeViewItem, the list of directories are added to the existing ones, see image below. In order to prevent that I would like to first clear the current list.
When I tried to delete the children using TreeViewItem.DeleteChildren from a TTreeViewItem I get an exception at another spot, see the picture below.
As to some questions: yes, I am sure I only add TTreeViewItems and this is the only Control I assign the OnClick event (import_directory_click). I have added the complete code and commented out the non-essentials to be sure.
I hope somebody tells me this functionality already exists (couldn't find it) but even then I would still like to know how to manage a TTreeView.
procedure TMain.import_initialize;
var
Item: TTreeViewItem;
drive: Char;
start: string;
begin
Directory_Tree.Clear;
{$IFDEF MSWINDOWS}
// When Windows, just present a list of all existing drives
for drive := 'C' to 'Z' do
begin
// A drive exists when its root directory exists
start := drive + ':\';
if TDirectory.Exists (start) then import_add (start, Directory_Tree);
end; // for
{$ELSE}
// All other systems are unix systems, start with root.
drive := '/';
start:= drive;
Item := import_add (TPath.GetPathRoot (start), DirectoryTree);
import_get_dirs (Item, start);
{$ENDIF}
start := TPath.GetSharedPicturesPath;
import_add (start, Directory_Tree);
if start <> TPath.GetPicturesPath
then import_add (TPath.GetPicturesPath, Directory_Tree);
// import_test_selection ('');
end; // import_initialize //
procedure TMain.import_directory_click (Sender: TObject);
var
TreeItem: TTreeViewItem;
obj: TFMXObject;
first_file: string;
begin
GridPanelLayout.Enabled := False;
if Sender <> nil then
begin
TreeItem := Sender as TTreeViewItem;
if TreeItem.IsExpanded then
begin
TreeItem.CollapseAll;
end else
begin
TreeItem.DeleteChildren; // <== this statement
import_get_dirs (TreeItem, TreeItem.Text);
{
first_file := find_first (TreeItem.Text, Selected_Images);
if first_file <> '' then
begin
Image.Bitmap.LoadFromFile (first_file);
GridPanelLayout.Enabled := True;
end; // if
}
TreeItem.Expand; // <== causes an exception over here
end; // if
end; // if
end; // import_directory_click //
procedure TMain.import_get_dirs (Start_Item: TTreeViewItem; start: string);
var
DirArray: TStringDynArray;
DirArraySize: Int32;
i: Int32;
begin
DirArray := TDirectory.GetDirectories (start);
DirArraySize := Length (DirArray);
for i := 0 to DirArraySize - 1
do import_add (DirArray [i], Start_Item);
end; // get_dirs //
function TMain.import_add (dir: string; owner: TControl): TTreeViewItem;
var
TreeItem: TTreeViewItem;
begin
TreeItem := TTreeViewItem.Create (owner);
TreeItem.text := dir;
TreeItem.OnClick := import_directory_click;
// TreeItem.Parent := owner;
owner.AddObject (TreeItem);
Result := TreeItem;
end; // import_add //

It seems that TreeItem.DeleteChildren deletes the item content site instead of the subitems.
I suggest to use this:
for i := TreeItem.Count - 1 downto 0 do
TreeItem.RemoveObject(TreeItem.Items[i]);

Related

How do I populate a Treeview via FTP

Scenario
I'm trying to duplicate the standard way to fill a Treeview with directories/folders from a folder structure, starting at the root, but using IdFTP to get the structure from a remote server instead of my local hard drive. I'd like the result to look similar to clients like Filezilla.
I used this reasonably standard code from the Swiss Delphi Centre (which works to display my hard drive's structure) and then modified it to use IdFTP.ChangeDir(Directory) and IdFTP.List instead of FindFirst() and FindNext().
Problem
I seem to have got myself in a muddle as it is not correctly 'unwinding' the recursion so that once it traverses down the /cpanel/cashes/config directories on the remote server it doesn't return and traverse all the other directories hanging off the root but exits the procedure without displaying anything else. Also it doesn't seem to show all the top level folders but this could be simply due to the order that IdFTP.List returns them in
Can anyone tell me what I have done wrong here?
If you can also tell me how I should get the root (/) shown as well that would be very helpful
(I've commented out displaying non directories as I only want folders at this stage)
What I expected to see Copied from Filezilla
What I did see Using a Ttreeview in Delphi
My Code
procedure TForm2.Button1Click(Sender: TObject);
var StartingDir : string;
begin
TreeView1.Items.BeginUpdate;
try
StartingDir := '/';
Screen.Cursor := crHourGlass;
TreeView1.Items.Clear;
FTPconnect; //procedure to connect to remote server
GetDirectories(TreeView1, StartingDir, nil, True);
FTPDisconnect; //procedure to disconnect from remote server
finally
TreeView1.Items.EndUpdate;
Screen.Cursor := crDefault;
end;
end;
procedure TForm2.GetDirectories(Tree: TTreeView; Directory: string; Item: TTreeNode; IncludeFiles: Boolean);
var
ItemTemp: TTreeNode;
DirItemType : TIdDirItemType ;
Filename , NewStartingDirectory: string;
i : Integer;
begin
Tree.Items.BeginUpdate;
IdFTP.ChangeDir(Directory);
IdFTP.List; //get directory of remote folder
i:=0;
repeat
DirItemType := IdFTP.DirectoryListing[I].ItemType;
Filename := IdFTP.DirectoryListing[I].FileName;
If (DirItemType = ditDirectory) and (Filename <> '.') and (Filename <> '..')then
begin
if DirItemType = ditDirectory then
Item := Tree.Items.AddChild(Item, Filename);
ItemTemp := Item.Parent;
if Directory = '/' then
NewStartingDirectory := Directory + Filename
else
NewStartingDirectory := Directory + '/' +Filename;
GetDirectories(Tree, NewStartingDirectory, Item, IncludeFiles);
Item := ItemTemp;
end
else
if IncludeFiles then
begin //this bit commented out as we only want to see directories
// if (Filename <> '.') and (Filename <> '..') then
// Tree.Items.AddChild(Item, Filename);
end;
inc(i);
until i = IdFTP.DirectoryListing.Count;
Tree.Items.EndUpdate;
end;
Swiss Delhpi Centre's code (for comparison)
procedure TForm1.Button1Click(Sender: TObject);
var
Node: TTreeNode;
Path: string;
Dir: string;
begin
Dir := 'c:\temp';
Screen.Cursor := crHourGlass;
TreeView1.Items.BeginUpdate;
try
TreeView1.Items.Clear;
GetDirectories(TreeView1, Dir, nil, True);
finally
Screen.Cursor := crDefault;
TreeView1.Items.EndUpdate;
end;
end;
procedure TForm1.GetDirectories(Tree: TTreeView; Directory: string; Item: TTreeNode; IncludeFiles: Boolean);
var
SearchRec: TSearchRec;
ItemTemp: TTreeNode;
begin
Tree.Items.BeginUpdate;
if Directory[Length(Directory)] <> '\' then Directory := Directory + '\';
if FindFirst(Directory + '*.*', faDirectory, SearchRec) = 0 then
begin
repeat
if (SearchRec.Attr and faDirectory = faDirectory) and (SearchRec.Name[1] <> '.') then
begin
if (SearchRec.Attr and faDirectory > 0) then
Item := Tree.Items.AddChild(Item, SearchRec.Name);
ItemTemp := Item.Parent;
GetDirectories(Tree, Directory + SearchRec.Name, Item, IncludeFiles);
Item := ItemTemp;
end
else if IncludeFiles then
if SearchRec.Name[1] <> '.' then
Tree.Items.AddChild(Item, SearchRec.Name);
until FindNext(SearchRec) <> 0;
FindClose(SearchRec);
end;
Tree.Items.EndUpdate;
end;
I've looked on SO here - too complicated and wrong language and here - similar to the Swiss Delphi Centre and here - wrong language and not sure what its doing.
if it's better to use a TlistView, can you please show me the equivalent code to use that instead?
Untested:
I made the TIdFTP variable a parameter, since TTreeView was also one and it should be done consistently, not archaic.
Using for loops instead of repeat until.
Eliminating IncludeFiles when it wasn't used anyway.
Eliminating weird logic to always get the new TreeNode's parent.
Not locking the TreeView anymore - do this once before calling this method and unlock it after calling - otherwise you do that dozens of times in vain.
Basic logic is as I wrote in the comments:
Store all folder strings into your own list and avoid recursion at this point.
Fix the path to be concatenated once, not with every iteration of a loop.
Go through that list to do the recursion - at this point the state of FTP is irrelevant and you won't mess up listings at different levels.
Of course, release the created instance of the StringList.
procedure TForm2.GetFolders
( Ftp: TIdFTP // The source, from which we read the content
; Tree: TTreeView // The destination, which we want to fill
; ParentNode: TTreeNode // Node under which all new child nodes should be created
; Path: String // Starting directory
);
var
NewNode: TTreeNode; // New child in the tree
Filename: String; // Check against unwanted folder entries
i: Integer; // Looping over both lists
sl: TStringList; // Collect folders only
begin
FTP.ChangeDir( Path );
FTP.List; // Entire remote listing
sl:= TStringList.Create; // Collect all entries we're interested in
try
for i:= 0 to FTP.DirectoryListing.Count- 1 do begin // For each entry
Filename:= FTP.DirectoryListing[i].FileName;
if (FTP.DirectoryListing[i].ItemType= ditDirectory) // Only folders
and (Filename<> '.')
and (Filename<> '..') then begin
sl.Add( Filename ); // Only the name, not the full path
end;
end;
// Do this only once
if Path<> '/' then Path:= '/'+ Path+ '/';
for i:= 0 to sl.Count- 1 do begin // All collected folders
NewNode:= Tree.Items.AddChild( ParentNode, sl[i] ); // Populate tree
GetFolders( Ftp, Tree, NewNode, Path+ sl[i] ); // Recursion of folder name + current path
end;
finally
sl.Free;
end;
end;
Untested, but should compile.

TMainMenu build menu item dynamic

On my system , the main menu is fully dynamic, is builded from data in the database.
I have a specific situation where some menu items need to be assembled before being displayed.
Let's assume that my menu has the following main items:
Files - Customer - Reports - About
When I click in Reports menu item must assemble the items before they are displayed.
I did an analysis of the code in TMainMenu, TMenu and TMenuItem class. Unfortunately I have not found a simple solution to the problem.
Exist a way to create these items before being displayed?
There is a trick you can use. You need to add one dummy TMenuItem under Reports and set its Visible property to False. Then add OnClick event to Reports item and do your populating logic there. Before you add new items you have to delete existing ones, but you should leave your dummy item intact.
Something like:
procedure TForm1.ReportItemClick(Sender: TObject);
var
Item: TMenuItem;
I: Integer;
begin
// Delete all items but first - dummy - one
for I := ReportItem.Count - 1 downto 1 do
ReportItem.Items[I].Free;
Item := TMenuItem.Create(ReportItem);
Item.Caption := 'abc';
// Item.OnClick := ...
// or
// Item.Action := ...
ReportItem.Add(Item);
Item := TMenuItem.Create(ReportItem);
Item.Caption := '123';
// Item.OnClick := ...
// or
// Item.Action := ...
ReportItem.Add(Item);
end;
Lets Suppose that you have an DS (TDataSet) how load all your data reports. And in the moment that you drop Reports Menu you can call UpdateMenuReport.
type
TMenuArray = array of TMenuItem;
var MyMenu: TMenuArray;
procedure TMain.MyClickPopupMenu(Sender: TObject);
begin
case TMenuItem(TMenuItem(Sender).Parent).Tag of
// do Something
end;
end;
procedure TMain.UpdateMenuReport;
procedure InitMyMenu(var AMenu: TMenuArray);
var i: Integer;
begin
if Length(AMenu)>0 then for i:= 0 to Length(AMenu)-1 do AMenu[i].Free;
SetLength(AMenu, 0);
end;
var j, i: integer;
begin
InitMyMenu(MyMenu);
Reports.Clear;
if DS.Active and (DS.RecordCount > 0) then
begin
SetLength(MyMenu, DS.RecordCount);
for i:= 0 to DS.RecordCount-1 do
begin
MyMenu[i] := TMenuItem.Create(Self);
MyMenu[i].Name := 'Reports_'+ IntToStr(i);
MyMenu[i].Caption := DS.FieldByname('NOM_REPORT').AsString;
MyMenu[i].Tag := DS.FieldByname('ID').AsInteger;
MyMenu[i].OnClick := MyClickPopupMenu;
end;
end;
end;

Programatically enable a menu item (and all it's parents) - Delphi

I need to selectively enable certain menu items based upon the status of the user. I've managed to get code to enable the actual items I want but I can't see how to enable all the parent menu items above each one that I enable in a multi-level menu. Without enabling them as well the menu item still can't be used as the user cannot reach it.
eg if I have
EditTop
EditSub1
Editsub2
EditSubSub1
EditSub3
I can enable EditSubSub1 but I also therefore need to enable Editsub2 and EditTop as well or it can't be reached by the user. That's what I would appreciate help with.
The code I have at the moment is the following (Assume that other code has given me a TstringList containing the menu names I want enabled)
First some code to disable everything.
procedure DisableMenu(AMenu: TMenuItem);
//recurses through all the menu and disables eveything
var
i: integer;
begin
for i := 0 to AMenu.Count - 1 do
begin
AMenu[i].enabled := false;
DisableMenu(AMenu[i]);
end;
end;
Then code that searches for and returns a TmenuItem based upon its name
(This came from
http://www.delphipages.com/forum/showthread.php?t=45723)
function FindMnuItem(Menu: TMenu; MenuName: string): TMenuItem;
procedure FindSubItems(mnuItem: TMenuItem);
var i: integer;
begin
for i:=0 to mnuItem.Count- 1 do
if mnuItem.Items[i].Name= MenuName then
begin
Result:= mnuItem.Items[i];
break;
end
else
FindSubItems(mnuItem.Items[i]);
end;
var i: integer;
begin
Result:= nil;
for i:= 0 to Menu.Items.Count -1 do
begin
if Menu.Items[i].name = MenuName then
begin
Result:= Menu.Items[i];
break;
end
else
if Result<> nil then
break
else
FindSubItems(Menu.Items[i]);
end;
end;
Finally the code I would like some help with. This selectively enables each menu item based upon the names in the Stringlist AllowedMenus but only those ones, not the ones above each one in the tree. How do I do that?
//first disable all menu items
DisableMenu(MainMenu1.Items);
//now enable the ones we want enabled
for i := 0 to AllowedMenus.count-1 do
begin
MenuName := AllowedMenus[i];
FindMnuItem(MainMenu1, MenuName).Enabled := true; //enable an item
end
All you need to do is walk up the menu tree using the TMenuItem.Parent property.
var vMenuItem : TMenuItem;
[...]
//first disable all menu items
DisableMenu(MainMenu1.Items);
//now enable the ones we want enabled
for i := 0 to AllowedMenus.count-1 do
begin
MenuName := AllowedMenus[i];
vMenuItem := FindMnuItem(MainMenu1, MenuName);
while Assigned(vMenuItem) do
begin
vMenuItem.Enabled := true; //enable an item
vMenuItem := vMenuItem.Parent;
end;
end
i think that u can use this function;
(D21 is your Actual Items):
procedure UpdateMenuParent(MyItemMenu: TMenuItem);
begin
TMenuItem(MyItemMenu).Enabled := true;
if TMenuItem(MyItemMenu).Parent <> nil then
UpdateMenuParent(TMenuItem(MyItemMenu).Parent);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
UpdateMenuParent(D21);
end;

WebBrowser component navigation through multiple pages does not work

Trying to navigate using WebBrowser component automatically through code it doesn't work. The navigation includes the login page and after that some other pages. The first page button login works fine. On second page the next button needed an application.processmessages before executing to make it work. On the next/third page I cannot make automatically the next button to work.
CODE:
//CLICK BUTTON
function clickForm1(WebBrowser: TWebBrowser; FieldName: string): Boolean;
var
i, j: Integer;
FormItem: Variant;
begin
Result := False;
//no form on document
if WebBrowser.OleObject.Document.all.tags('FORM').Length = 0 then
begin
Exit;
end;
//count forms on document
for I := 0 to WebBrowser.OleObject.Document.forms.Length - 1 do
begin
FormItem := WebBrowser.OleObject.Document.forms.Item(I);
for j := 0 to FormItem.Length - 1 do
begin
try
//when the fieldname is found, try to fill out
if FormItem.Item(j).Name = FieldName then
begin
FormItem.Item(j).click;
Result := True;
end;
except
Exit;
end;
end;
end;
end;
//SEARCH INSIDE THE MEMO
procedure TForm2.Button7Click(Sender: TObject);
var
i: Integer;
a: string;
begin
Memo1.Lines.Add('');
Memo1.Lines.Text := ' ' + Memo1.Lines.Text;
for i := 0 to Length(Memo1.Lines.Text) - Length(edit7.Text) do
begin
a := Copy(Memo1.Lines.Text, i, Length(edit7.Text));
if CheckBox1.Checked = True then //FIND CASE Sensitive
begin
if a = edit7.Text then
begin
find := True;
x := 2;
Memo1.Lines.Text := Copy(Memo1.Lines.Text, 2, Length(Memo1.Lines.Text) - 1);
Memo1.SetFocus;
Memo1.SelStart := i - 2;
Memo1.SelLength := Length(edit7.Text);
break;
end;
end
else
begin
if lowercase(a) = lowercase(edit7.Text) then
begin
Memo1.Lines.Text := Copy(Memo1.Lines.Text, 2, Length(Memo1.Lines.Text) - 1);
find := True;
x := 2;
Memo1.SetFocus;
Memo1.SelStart := i - 2;
Memo1.SelLength := Length(edit7.Text);
break;
end;
end;
end;
end;
//HTML TO MEMO
procedure TForm2.Button6Click(Sender: TObject);
var
iall : IHTMLElement;
begin
if Assigned(WebBrowser1.Document) then
begin
iall := (WebBrowser1.Document AS IHTMLDocument2).body;
while iall.parentElement <> nil do
begin
iall := iall.parentElement;
end;
memo1.Text := iall.outerHTML;
end;
end;
procedure TForm2.WebBrowser1DocumentComplete(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
Document: IHtmlDocument2;
CurWebrowser : IWebBrowser;
TopWebBrowser: IWebBrowser;
WindowName : string;
ovElements: OleVariant;
i: Integer;
begin
CurWebrowser := pDisp as IWebBrowser;
TopWebBrowser := (ASender as TWebBrowser).DefaultInterface;
if CurWebrowser=TopWebBrowser then
begin
button6.Click; // HTML TO MEMO
TRY
button7.Click; //SEARCH LOGIN FORM
if find=true then Begin
clickForm1(WebBrowser1, 'move'); //CLICK LOGIN BUTTON
End Else begin Null; End;
FINALLY find:=false; END;
TRY
button8.Click; //SEARCH HOME (AFTER LOGIN) FORM
if find1=true then Begin
Application.ProcessMessages;//NEEDED IN ORDER THE BUTTON TO BE PRESSED.
clickForm1(WebBrowser1, 'refresh'); //CLICK NEXT PAGE BUTTON
End;
FINALLY find1:=false;END;
TRY
button9.Click; //SEARCH WORKLIST FORM
if find2=true then Begin
clickForm1(WebBrowser1, 'next'); //CLICK NEW FORM BUTTON
End;
FINALLY find2:=false;END;
end;
end;
I'm not sure how much you know about working with Event Handlers in code.
Objects like Forms and WebBrowsers typically have one or more event properties that are used to define what happens when the event occurs. So, an event property is a property of an object that can hold the information necessary to invoke (call) a procedure (or function, but not usually) of the same object or another one. The procedure to call has to have the right "signature" for the type definition of the event. If it does then an "event handler" can be assigned to the event property in code, as I'll show below.
One can use event properties and event-handling code in Delphi in a simple way, without knowing any of this, just by going to the Events tab of the Object Inspector and double-clicking next to one of the event names. What that actually does is to create a new handler procedure and to assign it to the corresponding event property of the object (well, not quite, actually that assignment is done at run-time when the host form is loaded).
What I mean by "signature" is the routine type (procedure or function) and its list of parameters, and their types, in its definition.
So, for a WebBrowser, the signature of the OnDocumentComplete event is
procedure (Sender: TObject; const pDisp: IDispatch; var URL: OLEVariant);
The clever thing is that you can assign the OnDocumentComplete property to
any procedure of an object that has the exact same signature. The event type for the WB's OnDocumentComplete is defined in the import unit ShDocVw, btw
So, let's suppose you write three methods that contain the code you want to run
when the WB completes loading URLs A, B and C, respectively:
procedure TForm1.DocCompleteA(Sender: TObject; const
pDisp: IDispatch; var URL: OLEVariant);
begin
// Do your stuff for arrival at site/page A here
// Then update NavigationOK flag to reflect if you succeeded or failed
if NavigationOK then begin
WebBrowser1.OnDocumentComplete := DocCompleteB;
// Now navigate to site/page B
end
else
WebBrowser1.OnDocumentComplete := Nil;
end;
procedure TForm1.DocCompleteB(Sender: TObject; const
pDisp: IDispatch; var URL: OLEVariant);
begin
end;
procedure TForm1.DocCompleteC(Sender: TObject; const
pDisp: IDispatch; var URL: OLEVariant);
begin
end;
Then, you can assign the WB's OnDocumentComplete property to each of them in turn,
with something like the code at the end of DocCompleteA which updates the WB's OnDocumentComplete to the code needed for B, and so on, in turn. The NavigationOK variable is just a flag to indicate that our navigation stays "on course" as it progresses. If it gets set to false because something went wrong, we set the WB's OnDocumentComplete to Nil, so that it does nothing next time the event occurs.
Then, you can kick off the whole "tour" of sites with something like this:
procedure TForm1.NavigateSites;
begin
NavigationOK := True;
WebBrowser1.OnDocumentComplete := DocCompleteA;
WebBrowser1.Navigate(...); // Navigate to site A
end;
Of course, you don't have to do the updating of the WB's OnDocumentComplete property and navigation to the next URL in the current DocCompleteX. In fact, it's probably clearer if you do those if a higher level procedure like the NavigateSites one, and more easily maintainable, which can be important if you're navigating others' sites, which are apt to be changed without any prior warning.

Delphi: Shift-Up and Shift-Down in the Listview

Is there a feature in the Listview control to shift items up and down?
Not having worked with TListView very much (I mostly use database grids), I took your question as a chance to learn something. The following code is the result, it is more visually oriented that David's answer. It has some limitations: it will only move the first selected item, and while it moves the item, the display for vsIcon and vsSmallIcon is strange after the move.
procedure TForm1.btnDownClick(Sender: TObject);
var
Index: integer;
temp : TListItem;
begin
// use a button that cannot get focus, such as TSpeedButton
if ListView1.Focused then
if ListView1.SelCount>0 then
begin
Index := ListView1.Selected.Index;
if Index<ListView1.Items.Count then
begin
temp := ListView1.Items.Insert(Index+2);
temp.Assign(ListView1.Items.Item[Index]);
ListView1.Items.Delete(Index);
// fix display so moved item is selected/focused
ListView1.Selected := temp;
ListView1.ItemFocused := temp;
end;
end;
end;
procedure TForm1.btnUpClick(Sender: TObject);
var
Index: integer;
temp : TListItem;
begin
// use a button that cannot get focus, such as TSpeedButton
if ListView1.Focused then
if ListView1.SelCount>0 then
begin
Index := ListView1.Selected.Index;
if Index>0 then
begin
temp := ListView1.Items.Insert(Index-1);
temp.Assign(ListView1.Items.Item[Index+1]);
ListView1.Items.Delete(Index+1);
// fix display so moved item is selected/focused
ListView1.Selected := temp;
ListView1.ItemFocused := temp;
end;
end;
end;
You have two options:
Delete them and then re-insert them at the new location.
Use a virtual list view and move them in your data structure.
My routine for doing the first of these options is like this:
procedure TBatchTaskList.MoveTasks(const Source: array of TListItem; Target: TListItem);
var
i, InsertIndex: Integer;
begin
Assert(IsMainThread);
BeginUpdate;
Try
//work out where to move them
if Assigned(Target) then begin
InsertIndex := FListItems.IndexOf(Target);
end else begin
InsertIndex := FListItems.Count;
end;
//create new items for each moved task
for i := 0 to high(Source) do begin
SetListItemValues(
FListItems.Insert(InsertIndex+i),
TBatchTask(Source[i].Data)
);
Source[i].Data := nil;//handover ownership to the new item
end;
//set selection and focus item to give feedback about the move
for i := 0 to high(Source) do begin
FListItems[InsertIndex+i].Selected := Source[i].Selected;
end;
FBatchList.ItemFocused := FListItems[InsertIndex];
//delete the duplicate source tasks
for i := 0 to high(Source) do begin
Source[i].Delete;
end;
Finally
EndUpdate;
End;
end;
The method SetListItemValues is used to populate the columns of the list view.
This is a perfect example of why virtual controls are so great.

Resources