views:

256

answers:

1

I have two listboxes. The listbox1 contains a list of the DB names. Listbox2, on the other hand, has a list the titles of the content associated by the DB on listbox1. Basically you click on listbox1 and it loads into listbox2 all the titles for the content of the DB.

I want to implement now a drag and drop feature. I know how to drag between two listboxes; that's not the problem. What I am trying to implement is the following:

  1. click on a title in listbox2

  2. drag item INTO an item in lisbox1

  3. the title is now part of the DB pointed by the item in listbox1

Now, all the backend code to move the actual data is already in coded. How can I make the listbox1 select (and know) the item where the mouse is about to drop the item from the listbox2? By implementing a simple drag and drop between the two listboxes will result on the item from listbox2 being added into listbox1 since I cannot select an item in listbox1 while i am dragging something.

I hope I explained this the right way.

Code is appreciated.

+3  A: 

If I understand correctly, you're trying to see what item is being dropped on. What you need is the ItemAtPos function of the ListBox. It takes a TPoint parameter and the OnDragDrop event handler has the X and Y coordinates.

In this example, ListBox2 is the Source, and ListBox1 is the control being dropped onto. iItem gives me the ItemIndex of the ListBox1 item being dropped onto.

procedure TForm1.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  iItem: Integer;
  MyPoint: TPoint;
begin
  MyPoint.X := X;
  MyPoint.Y := Y;

  iItem := ListBox1.ItemAtPos(MyPoint, True);

  ListBox1.Items.Insert(iItem, ListBox2.Items[ListBox2.ItemIndex]);
end;

There is no range checking here, it's just an example to illustrate the ItemAtPos function.

_J_
The name of the item then I assume would be in Items.name[Listbox2.ItemIndex]?
Uri
Uri, ListBox2.Items[ListBox2.ItemIndex] contains the text of the item being dropped.
_J_
Thanks. So since I don't want to add the new item I am going to remove the last line (ListBox1.Items.Insert). How can you highlight the item on listbox1 when the mouse is on top of it? You don't know where it's going to go until you release the mouse button
Uri
You can use again ItemAtPos in OnDragOver.
Sertac Akyuz
I tried that but i don't know how to make the item be highlighted.
Uri
To appear highlighted, an item must be selected, so change the target listbox's ItemIndex property: `TListBox(Sender).ItemIndex := iItem;`
Rob Kennedy
Yes, what Rob said :o)
_J_
Thanks, not exactly what I meant but I'll accept the answer. What I meant is *when* when mouse enters the listbox1 the highlighted item should follow the mouse, so if the mouse pointer with the dragged item is on top of Item1 then Item1 appears highlighted, if I moved and it's now on top of Item8 then Item8 is highlighted.
Uri
Thanks. You can change the ListBox1.ItemIndex in the OnMouseMove event to do what you want.
_J_