Skip to main content

How to Drag External File in the ListView Using C#

Screenshot
Body
This time, I will teach you how to drag an external file in the ListView using C#. By using this kind of method this allows you to easily drag and drop an image in the Listview. You might encounter this kind of problem in programming, but you will only achieve it once you follow the steps below.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Add a ListView and PictureBox inside the Form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, declare an item in the listview control.
  1.  
  2. ListViewItem lstviewItem;

Step 4

Double click the form and add the following code to setup a ListView and PictureBox properties in the first load of a form.
  1.  
  2. listView1.AllowDrop = true;
  3. listView1.View = View.Details;
  4. listView1.AllowDrop = true;
  5. listView1.Columns.Add("File");
  6. listView1.Columns[0].Width = 500;
  7.  
  8. pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

Step 5

Write the following code for the DragEnter event of the ListView.
  1.  
  2. private void listView1_DragEnter(object sender, DragEventArgs e)
  3. {
  4. if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
  5. {
  6. e.Effect = DragDropEffects.All;
  7. }
  8. }
  9.  

Step 6

Write the following code for the DragDrop event of the ListView.
  1.  
  2. private void listView1_DragDrop(object sender, DragEventArgs e)
  3. {
  4. try
  5. {
  6. string[] file;
  7. file = (string[])e.Data.GetData(DataFormats.FileDrop);
  8. foreach(string files in file)
  9. {
  10. lstviewItem = new ListViewItem(files);
  11. listView1.Items.Add(lstviewItem);
  12. }
  13.  
  14. }
  15. catch(Exception ex)
  16. {
  17. MessageBox.Show("error : " + ex.Message);
  18. }
  19.  
  20. }

Step 7

Double click the ListView and do the following code to display the image in the PictureBox when the ListViewItem is selected.
  1.  
  2. if (listView1.SelectedItems.Count == 0) return;
  3. pictureBox1.Image = Image.FromFile(listView1.SelectedItems[0].Text);
  4. this.Text = listView1.SelectedItems[0].Text;
The complete sourcecode is included. You can download it and run it on your computer. For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment