0

我最近试图找到一些代码来将一行从一个数据网格视图拖放到 WinForms 应用程序中的另一个数据网格视图。我最终找到了有效的代码,但有一个小问题。当我在dataGridView2中选择一行拖动到dataGridView1时,如果我不小心并且马虎,我不小心将该行拖到dataGridView2的另一行中。它就像它只是消失在dataGridView2的另一行中。有没有办法检测到如果被拖动的行不在dataGridView1中,则不允许将其丢弃?

 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);
        }

    }
4

1 回答 1

1

将 datagridview2 的 AllowDrop 属性设置为 false。

于 2013-09-25T13:50:41.350 回答