Tuesday, November 21, 2006

Drag and Drop Objects

Did you know drag-and-drop supports objects and not just strings? In a Winforms app load up a list box with objects. Make sure to define a ToString() method on your object, Add another control with the AllowDrop property set to True. Implement the MouseDown event on the list as:


private void listBox1_MouseDown(object sender, MouseEventArgs e)

{

if (listBox1.SelectedItem != null )

listBox1.DoDragDrop(listBox1.SelectedItem,

DragDropEffects

.Move);

}

Then implement the following 2 events on the destination control:

private void flowLayoutPanel1_DragEnter(object sender, DragEventArgs e)

{

if (e.Data.GetDataPresent(typeof(Script)))

e.Effect = DragDropEffects.Move;

}

private void flowLayoutPanel2_DragDrop(object sender, DragEventArgs e)

{

Script x = e.Data.GetData(typeof(WindowsApplication1.Script)) as Script;

//todo now do something with the Script x

}

Note that the Script object was the object that was dropped.

No comments: