This post describes how to do a simple drag drop operation in a WinForm. You can drag drop the text from one button to the other. The above video shows the final application at work. The same idea can be extended according to the requirement.
I have used Microsoft Visual C# Express Edition that can be downloaded from href=”http://msdn.microsoft.com/vstudio/express/visualcsharp/download”>here. .Net 2.0 framework should be installed to run this program.
I started with creating a new project, DragDropDemo, in Visual C# IDE. Next I renamed the default Form1.cs to MainForm.cs and opened it in the Form Designer.
I added two buttons – one acting as the source for drag drop and the other acting as the target. I renamed the two buttons from button1 to sourceButton and button2 to targetButton.
Next I changed the Text property of the sourceButton to “Hello World!” and that of the targetButton to “Drag text on me”.
Now the stage has been set to get into the actual drag drop stuff. Let’s have a look at how a drag drop works.
- The user clicks on a control like a Button and moves the mouse while holding down the mouse button.
- The user moves the mouse over another control and if this control can receive the drop, the mouse cursor changes to a special icon. The control receives the information when the user releases the mouse.
- The control that has received the information operates on it.
First thing is to enable the targetButton to receive a drop by setting the AllowDrop property to true.
Second, add event handler for sourceButton Mouse Down event. The information sent for the drag drop is the text on the sourceButton. DragDropEffect desides the type of cursor that will be shown when the information is dropped on the targetButton.
private void sourceButton_MouseDown(object sender, MouseEventArgs e)
Next, add the event handler for Drag Enter event. Check for the format of the data present in the drop and if that is string, change the cursor accordingly to show that the drop is possible and the information will be copied from the source to target.
private void targetButton_DragEnter(object sender, DragEventArgs e)
e.Effect = DragDropEffects.Copy;
e.Effect = DragDropEffects.None;
Now the targetButton can receive the text from the sourceButton. What is left is to work on this dropped information Here I have changed the targetButton’s text to the dropped text that is “Hello world” in our case.
For this we need to write the event handler for the Drag Drop event of th targetButton. Here it is.
private void targetButton_DragDrop(object sender, DragEventArgs e)
targetButton.Text = e.Data.GetData(DataFormats.StringFormat);
You can see the application at work here.