gudguy

Anyone knows how to code a drag and drop operation so I can move my UserControl (or any windows Control) to any panels of a TableLayoutPanel.

regards,
gudguy



Re: Visual C# Express Edition Drag and Drop a Control on TableLayoutPanel

gudguy

anyone




Re: Visual C# Express Edition Drag and Drop a Control on TableLayoutPanel

Yan-Fei Wei - MSFT

hi,gudguy

If you just want to move your control to the panel, you can set the location of your control to the appropriate location in the panel.But if you want to drag/drop with mouse,you should take the following steps:
1. The destination control needs to have its AllowDrop property set to true;
2. In the source controlí»s MouseDown event, call its DoDragDrop method;
3. Handle the destination controlí»s DragEnter, DragOver and DragDrop events

Assume that we should drag a button named "btnDrag" to a TableLayoutPanel named "tableLayoutPanelDrop", you can take the following code as a reference.

Code Block

Point ptOriginal= Point.Empty; //the original location of the button

......

//

private void btnDrag_MouseDown(object sender, MouseEventArgs e)
{
ptOriginal = new Point(e.X, e.Y);
this.tableLayoutPanelDrop.AllowDrop = true;
((Control)sender).DoDragDrop(sender, DragDropEffects.All);
}

//

private void tableLayoutPanelDrop_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.Windows.Forms.Button)))
e.Effect = DragDropEffects.All;

}

//

private void tableLayoutPanelDrop_DragOver(object sender, DragEventArgs e)
{
((Control)e.Data.GetData(typeof(System.Windows.Forms.Button))).Location =
this.PointToClient(new Point(e.X - ptOriginal.X, e.Y - ptOriginal.Y));
((Control)e.Data.GetData(typeof(System.Windows.Forms.Button))).BringToFront();

}

//

private void tableLayoutPanelDrop_DragDrop(object sender, DragEventArgs e)
{
((Button)e.Data.GetData(typeof(System.Windows.Forms.Button))).BringToFront();
}