drag and drop samples

sample drag and drop methods

Download draganddrop.zip

Synopsis:

draganddrop.cs


draganddrop.cs

Synopsis
//WARNING: NOT UNITTESTED
using System;
using System.Drawing;  //required for Point()
using System.Windows.Forms;

//sample code for a drag and drop
//shows how rows from listbox1 can be dropped onto listbox2
public class draganddrop
{
  ListBox mList1 = new ListBox();
  ListBox mList2 = new ListBox();

  //... rest of the gui code goes here

  //This detects the beginning of the drag. The left mouse button
  //is pressed within listbox1
  public void mList1_MouseDown(object sender, MouseEventArgs e)
  {
    //get the row index from the pixel the mouse was pressed over
    int index = mList1.IndexFromPoint(new Point(e.X,e.Y));

    //if it is an invalid index, then it the mouse was over some other
    //part of the listbox
    if(index < 0) return;
    
    //this is the contents of the listbox row
    //assume a string here but any object can be used
    string s = (string) mList1.Items[index];

    //The .Copy will set the cursor to a '+'
    //and set the type for the drop target.
    mList1.DoDragDrop(s, DragDropEffects.Copy);
  }
  public void mList2_DragEnter(object sender, DragEventArgs e) 
  {
    //If the data present is not of type Text, then we can't accept the drop
    if(!e.Data.GetDataPresent("Text")) return;

    //we can only accept drops of type 'Copy'
    //if the drag is not of type 'Copy' then the user 
    //sees the circle/slash symbol
    e.Effect = DragDropEffects.Copy;
  }
  public void mList2_DragDrop(object sender, DragEventArgs e)
  {
    //the user let go of the mouse button.
    string s = (string)e.Data.GetData("Text");
    
    //perform the action...
    mList2.Items.Add(s);
  }
}






Contact me about content on this page using john_web-at-arrizza-dot-com
For Web Master or site problems contact: webadmin-at-arrizza-dot-com
Copyright John Arrizza (c) 2001,2002,2003,2004,2005,2006,2007