FOLLOW US
softpcapps Software CODE HELP BLOG

Shareware and free Open Source Windows Software Applications and free Online Tools

How to implement Drag and Drop of Files feature

At first we have to set the "AllowDrop" property of the control where the files are going to be droped to true.
Afterwards we have to add the DragEnter, DragOver and DragDrop event handlers for the control.
The DragEnter and DragOver event handlers will be used to show the "Copy" mouse cursor effect when draging files over the control.
When the drop occurs we will get the list of files that were dropped with
	
 
string[] filez = (string[])e.Data.GetData(DataFormats.FileDrop);

Then we can check the files if they are of the correct file type and use them, add them to the list e.t.c.
	

	private void dgVideo_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
            {                
                e.Effect = DragDropEffects.All;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void dgVideo_DragOver(object sender, DragEventArgs e)
        {            
            if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void dgVideo_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
            {
				// get list of files that were dropped
				
                string[] filez = (string[])e.Data.GetData(DataFormats.FileDrop);

                for (int k = 0; k < filez.Length; k++)
                {                    
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        
						// assess if we should add file
						
						if (ShouldAddFile(filez[k]))
						{
								// then add file
								AddFile(filez[k]);
						}
						
                    }
                    finally
                    {
                        this.Cursor = null;
                    }
                }
            }
        }
		
		// use your own function here - just a sample
		
		private bool ShouldAddFile(string filepath)
		{
			if (System.IO.Path.GetExtension(filepath).ToLower()==".pdf")
			{
					return true;
			}
			else
			{
					return false;
			}
		}
		
		// use your own function here - just a sample
		
		private void AddFile(string filepath)
		{
				DataRow dr=dataTable.NewRow();
				dr["filepath"]=filepath;
				dt.Rows.Add(dr);
		}