views:

259

answers:

2

I'm trying to build a form where the user can drag a label and drop it on a text box. I can find an AllowDrop in the text box, but there is no property such as "AllowDrag" in the label. Also, I created methods for all the drag & drop events for the label (DragEnter, DragLeave, etc) but none of them seem to work. I can not figure out how to drag. How do I handle it?

        private void label1_Click(object sender, EventArgs e)
    {

        // This one works
        status.Text = "Click";
    }

        private void label1_DragOver(object sender, DragEventArgs e)
    {

        // this and the others do not
        status.Text = "DragOver";
    }

    private void label1_GiveFeedback(object sender, GiveFeedbackEventArgs e)
    {
        status.Text = "GiveFeedback";
    }

    private void label1_DragDrop(object sender, DragEventArgs e)
    {
        status.Text = "DragDrop";
    }

    private void label1_DragEnter(object sender, DragEventArgs e)
    {
        status.Text = "DragEnter";
    }

    private void label1_DragLeave(object sender, EventArgs e)
    {
        status.Text = "DragLeave";
    }

    private void label1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e)
    {
        status.Text = "QueryContinueDrag";
    }
+1  A: 

You have to manually move the label by keeping a bool that you make true when you press down and false when you let go of the button, and in your mousemove event you move the control to the mouse when the bool is true.

You can find an example here.

Blindy
+7  A: 

There is no "AllowDrag" property, you actively start the D+D with the DoDragDrop() method. And the event handlers need to be on the D+D target, not the source. A sample form, it needs a label and a text box:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      label1.MouseDown += new MouseEventHandler(label1_MouseDown);
      textBox1.AllowDrop = true;
      textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);
      textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);
    }

    void label1_MouseDown(object sender, MouseEventArgs e) {
      DoDragDrop(label1.Text, DragDropEffects.Copy);
    }
    void textBox1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.Text)) e.Effect = DragDropEffects.Copy;
    }
    void textBox1_DragDrop(object sender, DragEventArgs e) {
      textBox1.Text = (string)e.Data.GetData(DataFormats.Text);
    }
  }
Hans Passant
exactly what I need. Thank you.
Paulo Guedes