anako
anako

Reputation: 125

Drag and Drop Windows Forms: Controls disappear after dragging

I need to drag labels between the panels. But when I'm trying to drop a label even within the initial panel, it disappears. Here is the code of the methods I use:

private void label1_MouseDown(object sender, MouseEventArgs e)
{
     if (e.Button == MouseButtons.Left)
     DoDragDrop(sender, DragDropEffects.All);
}


private void panel_DragEnter(object sender, DragEventArgs e)
{
    e.Effect = DragDropEffects.All;
}


private void panel_DragDrop(object sender, DragEventArgs e)
{
    Label src = e.Data.GetData(typeof(Label)) as Label;
    src.Location = PointToClient(new Point(e.X, e.Y));
}

AllowDrop is enabled for the panels. Why do the labels disappear and how can I fix it?

Upvotes: 1

Views: 775

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39122

The Label is still contained by the Form, so it is simply going behind the Panel.

Either...

(1) Bring the Label to the Front:

    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Label src = e.Data.GetData(typeof(Label)) as Label;
        src.Location = this.PointToClient(new Point(e.X, e.Y));
        src.BringToFront();
    }

or,

(2) Make the Panel contain the Label, and adjust the coordinates to the Panel's client coord system:

    private void panel1_DragDrop(object sender, DragEventArgs e)
    {
        Panel pnl = sender as Panel;
        Label src = e.Data.GetData(typeof(Label)) as Label;
        src.Location = pnl.PointToClient(new Point(e.X, e.Y));
        pnl.Controls.Add(src);
    }

Upvotes: 1

Related Questions