- This topic explains How to Drag and Drop files in C#.
- Here you can drag drop files from system to the ListView control in C#.
Drag and Drop – How to Drag and Drop files in C#
- Drag and Drop is used to move items from one place to another through dragging, it can be moved around by holding the mouse down on them, and that they’ll get appropriate visual feedback when they’re over a spot where the item can be dropped.
- To begin a drag and drop operation, you have to call the DoDragDrop method of a Windows Forms control.
- The DoDragDrop method is implemented on the System.Windows.Forms.Control class, which means that it is available on all controls within the Windows Forms namespace.
ListBox Class – How to Drag and Drop files in C#
- ListBox class represents a Windows control to display a list of items.
- Syntax for ListBox
|
1 2 3 4 |
[ClassInterfaceAttribute(ClassInterfaceType.AutoDispatch)] [DefaultBindingPropertyAttribute("SelectedValue")] [ComVisibleAttribute(true)] public class ListBox : ListControl |
How to Drag and Drop Files in C# – Working
- Add a ListBox control to a form and set its AllowDrop property to True in C#.
- Drag the files from system and drop to the ListBox control, In ListBox the dropped files will be added.
How to Drag and Drop files in C# – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace TestC { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void listBox1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.All; } } private void listBox1_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] MyFiles = null; int i = 0; // Assign the files to an array. MyFiles =(string[]) e.Data.GetData(DataFormats.FileDrop); // Loop through the array and add the files to the list. for (i = 0; i <= MyFiles.Length - 1; i++) { listBox1.Items.Add(MyFiles[i]); } } } } } |
How to Drag and Drop files in C#






