0
votes

I was recently trying to find some code to drag and drop a row from one datagridview to another datagridview in a WinForms app. I eventually found code that works, but there's one little problem. When I select a row in dataGridView2 to drag to dataGridView1, if I'm not careful and being sloppy, I accidentally drag the row into another row in dataGridView2. Its like it just disappears into another row in dataGridView2. Is there a way to detect that if the row being dragged isn't in dataGridView1, don't allow it to be dropped?

 dataGridView2.MouseMove += new MouseEventHandler(dataGridView2_MouseMove);
 dataGridView1.DragEnter += new DragEventHandler(dataGridView1_DragEnter);
 dataGridView1.DragDrop += new DragEventHandler(dataGridView1_DragDrop);

 void dataGridView1_DragDrop(object sender, DragEventArgs e)
    {
        DataGridViewRow row = e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;
        if (row != null)
        {
            DataGridViewRow newrow = row.Clone() as DataGridViewRow;
            for (int i = 0; i < newrow.Cells.Count; i++)
            {
                newrow.Cells[i].Value = row.Cells[i].Value;
            }

            this.dataGridView1.Rows.Add(newrow);

        }
    }

    void dataGridView1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(DataGridViewRow)))
        {
            e.Effect = DragDropEffects.Copy;
        }
    }

    void dataGridView2_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            this.dataGridView2.DoDragDrop(this.dataGridView2.CurrentRow, DragDropEffects.All);
            this.dataGridView2.Rows.Remove(this.dataGridView2.CurrentRow);
        }

    }
1

1 Answers

1
votes

Set AllowDrop Property of datagridview2 to false.