Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Drag and Drop Files to a DataGridView and record the file names into the cells C#?

I have created a binded DataGridView that has one single column. I want to be able to drag and drop files onto the DataGridView and store only the filenames (Path and Name) into the cells of the column. I have been doing research and the way to do it is to use the events DragDrop and DragEnter and have tried a couple different things but none have worked. Does anyone know how to do this?

My code:

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

    private void PlaylistDataGridDragDrop(object sender, DragEventArgs e)
    {      
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            var files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (var filePath in files)
            {
                var a = (DataRowView) PlaylistBindingSource.AddNew();
                a.BeginEdit();
                a[0] = filePath;
                a.EndEdit();
            }
        }
    }
like image 457
cougar Avatar asked Jan 23 '26 10:01

cougar


1 Answers

You'll need to implement the DragEnter and DragDrop events like you say. Here is a good article on how to do this. You added your code as I was typing. You just need to adjust how you add items to your DataGridView. You need to add a new row and then address the last row:

PlaylistDataGrid.Rows.Add();
PlayListDataGrid[0,PlaylistDataGrid.RowCount-1].Value = filePath

This assumes you want to put the data in the first column of the DataGridView.

like image 54
Fr33dan Avatar answered Jan 25 '26 23:01

Fr33dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!