CsharpChico
Junior Poster in Training
72 posts since May 2010
Reputation Points: 12
Solved Threads: 8
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace DragDrop
{
public partial class Form1 : Form
{
private Label label1;
private Label label2;
private Label label3;
private TextBox dropTxb;
public Form1()
{
// Init the form.
InitializeComponent();
// Install our controls.
label1 = new Label();
label2 = new Label();
label3 = new Label();
dropTxb = new TextBox();
// Place 3 labels
label1.Location = new Point(100, 30);
label1.Text = "One";
label2.Location = new Point(100, 60);
label2.Text = "Two";
label3.Location = new Point(100, 90);
label3.Text = "Three";
// and a textbox on the form.
dropTxb.Location = new Point(100, 180);
this.dropTxb.Size = new Size(100, 20);
dropTxb.AllowDrop = true; //essential
// Handle mousedowns of all the labels with the same method.
label1.MouseDown += new MouseEventHandler(labelMouseDown);
label2.MouseDown += new MouseEventHandler(labelMouseDown);
label3.MouseDown += new MouseEventHandler(labelMouseDown);
// Install two drageventhandlers for our textbox.
dropTxb.DragEnter += new DragEventHandler(this.dropTxb_DragEnter);
dropTxb.DragDrop += new DragEventHandler(dropTxb_DragDrop);
// Add our controls to the controls collection of the form.
this.Controls.Add(label1);
this.Controls.Add(label2);
this.Controls.Add(label3);
this.Controls.Add(dropTxb);
}
void labelMouseDown(object sender, MouseEventArgs e)
{
// We know sender is a label find out which.
Label Lbl = sender as Label;
// Get the label text and start the whole thing up.
Lbl.DoDragDrop(Lbl.Text, DragDropEffects.Copy);
}
private void dropTxb_DragEnter(object sender, DragEventArgs e)
{
// Check if the data we are dragging is text.
// Data gets the IDataObject that contains the data associated with the dragevent.
if (e.Data.GetDataPresent("Text"))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void dropTxb_DragDrop(object sender, DragEventArgs e)
{
// Get the textdata object and cast to string
// Data gets the IDataObject that contains the data associated with the dragevent.
dropTxb.Text = e.Data.GetData(DataFormats.Text) as String;
// Show we were here
// Had to do this for Momerath and Mitja LOL
StringBuilder sb = new StringBuilder();
sb.Append("The text ");
sb.Append("\"");
sb.Append(dropTxb.Text);
sb.Append("\"");
sb.Append(" was dropped in the textbox.");
MessageBox.Show(sb.ToString());
}
}
}