Header Ads

Drag and Drop made easy

In this article I will make implementing Drag and Drop simpler to understand and use it in your .Net Applications. The basic thing in Drag and Drop is to enable it. There are two parts of enabling the feature. One is on the Control on which you want the feature to work. Second is in the event handler of the Drag and Drop event. For this article I am specifically using ‘TextBox’ control.

For the first part, you can do this by setting the ‘AllowDrop’ Property of the control to ‘True’. Now go to the ‘Events’ tab of the control. You will find four events ‘DragDrop’, ‘DragEnter’, ‘DragLeave’, ‘DragOver’. You have to use 'DragOver' event to alongwith any of the other events for your Drag and Drop.

Note : Use only one of the event. If you set more than one event, you may get undesirable results or if the code for events is the same it may duplicate the data inserted.

For the second part we will select the ‘DragOver’ as the event for our use. In the event handler you get two parameters of ‘object’ type and ‘DragEventArgs’. To enable it, use the ‘Effects’ property of second parameter passed to the event handler of the type ‘DragEventArgs’. The code should look like this:

e.Effect = DragDropEffects.Copy;

After this we have to get the Data from the Drag and Drop event and insert it into the Control. For fetching the Data it is very important for us to understand Data Formats. In Windows we can literally drag anything from file to a single alphabet or a digit. Since we are using ‘TextBox’ control, only Text Data can be inserted. For this we will select the ‘DragDrop’ as the event for our use. Again we have to use the second parameter passed to the event handler of the type ‘DragEventArgs’. This time we will work with ‘Data’.GetData() method to retrieve the Text Data. In this method we specify the Data Format of the Data we want to retrieve which is Text. The following line will do this for us:

textBox2.Text = e.Data.GetData(DataFormats.Text).ToString();

‘textBox2’ is the name of the ‘TextBox’ control in my Form.

Done. You application is now Drag and Drop ready

No comments:

Powered by Blogger.