Drag and drop controls in windows application


This snippet is used to drag the controls from a panel and drop the controls to another panel.

This drag and drop functionality we can easily implement in windows applications.

Using drag enter and drag drop event handler we can drag the controls from
one panel to another panel.

Add the DragEnter and DragDrop event handler to the panel. Which panel wants
to receive the controls.

Ex:

I have two panels left and right. Left panel contain 3 controls (Button, checkbox...)
and right panel contain no controls. If i want to drag the controls from left panel and
move to right panel, then you should add these two event handler in right panel.


pnlRight.DragEnter += new DragEventHandler(pnlLeft_DragEnter);
pnlRight.DragDrop+=new DragEventHandler(pnlRight_DragDrop);


Add the above line of codes in the form_load method.

Whenever you add the controls to left panel you must add this MouseDown eventhandler
to that control then add to the left panel.

Ex:

If you want to add the button controls to left panel initially, then add this event,

button1.MouseDown += new MouseEventHandler(button1_MouseDown);



In this button1_mouseDown event call the dragand drop method,

void button1_MouseDown(object sender, MouseEventArgs e)
{
button1.DoDragDrop(sender, DragDropEffects.Copy);
}



Add the following code in DragDrop events,

void pnlRight_DragDrop(object sender, DragEventArgs e)
{
string strctrlName = e.Data.GetFormats()[0].ToString();

if(strctrlName.Contains("Button"))
pnlRight.Controls.Add(e.Data.GetData((e.Data.GetFormats()[0])) as Button);
else if (strctrlName.Contains("CheckBox"))
pnlRight.Controls.Add(e.Data.GetData((e.Data.GetFormats()[0])) as CheckBox);
else if(strctrlName.Contains("CheckedListBox"))
pnlRight.Controls.Add(e.Data.GetData((e.Data.GetFormats()[0])) as CheckedListBox);
}


Add the following code in Drag enter events,

void pnlLeft_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}



Here i attached the sample application download and try it.


Attachments

  • Drag and drop controls in windows application (38182-5534-DragandDrop.rar)
  • Related Articles

    Write a Console Application for beginners

    .NET framework contains Console application,Windows applications usually called as Win Apps,Web applications,Mobile applications,Web Services.Let us know how to write a simple Hello World using Console Application in the Visual Studio.NET framework tool 2008.

    More articles: Drag and drop Controls Windows application Drag Drop Windows Application

    Comments

    Guest Author: Nitin17 Apr 2012

    Thanks, nice code and good explanation for clear understanding. It helped me a lot.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: