Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Good afternoon,

I have a small program that contains a DataGridView, that I would like the ability to drag and drop PDF files onto.

I have got the program working fine with one exception

If the current row is the last row where you type in new data, then I get the error

Error: Operation is not valid due to the current state of the object.

I understand why I get this error. I presume you need to commit or cancel any changes you have made to the grid before adding anything new. I just don't know how to do this.

public partial class MainForm : Form
{
    BindingList<PDFFile> PDFList = new BindingList<PDFFile>();
    public MainForm()
    {
        InitializeComponent();
        dgv.DataSource = PDFList;
    }

    void DgvDragDrop(object sender, DragEventArgs e)
    {
        PDFFile pdfFile;
        if (dgv.CurrentRow.IsNewRow)
            MessageBox.Show("Error will occur");
        string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop);
        foreach (string file in files)
        {
            try
            {
                pdfFile = new PDFFile();
                pdfFile.Path = file;

                PDFList.Add(pdfFile);
            }
            catch (Exception error)
            {
                MessageBox.Show("Error: " + error.Message);
            }
        }
    }

    void DgvDragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
            e.Effect = DragDropEffects.Copy;
    }
}

public class PDFFile
{
    public string Path {get; set;}
}


What I have tried:

I can stop this from happening by unbinding before adding to the PDFList, and then binding again once done. But this is a horrible way to do it.

I have also tried

if (dgv.CurrentRow.IsNewRow || dgv.IsCurrentRowDirty)
    dgv.EndEdit(); 

I am sure there is a simple solution to this, but I cannot find anything in the forums

Any help would be greatly appreciated.
Posted
Updated 2-Apr-19 18:58pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900