在多个表单上的两个网格视图之间拖放

时间:2015-01-30 10:37:03

标签: c# datagridview drag-and-drop

所以我有一个主窗体,然后是多个带有数据网格视图的窗口。

我希望能够将数据与主窗口交换到子窗口,反之亦然。

我的主要表格是:

private Rectangle dragBoxFromMouseDown;
    private object valueFromMouseDown;

    private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {
        var hittestInfo = dataGridView1.HitTest(e.X, e.Y);
        if (hittestInfo.RowIndex != -1 && hittestInfo.ColumnIndex != -1)
        {
            valueFromMouseDown = dataGridView1.Rows[hittestInfo.RowIndex];
            if (valueFromMouseDown != null)
            {
                Size dragSize = SystemInformation.DragSize;
                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
            }
        }
        else
            dragBoxFromMouseDown = Rectangle.Empty;
    }

    private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
        {
            if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y))
            {
                DragDropEffects dropEffect = dataGridView1.DoDragDrop(valueFromMouseDown, DragDropEffects.Copy);
            }
        }
    }

然后在我的孩子表格上:

        private void dataGridView1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(typeof(System.String)))
            e.Effect = DragDropEffects.Copy;
        else
            e.Effect = DragDropEffects.None;
    }

    private void dataGridView1_DragOver(object sender, DragEventArgs e)
    {
        e.Effect = DragDropEffects.Copy;
    }

    private void dataGridView1_DragDrop(object sender, DragEventArgs e)
    {
        Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
        DataGridView.HitTestInfo hit = dataGridView1.HitTest(clientPoint.X, clientPoint.Y);

        if (hit.RowIndex != -1)
        {
            dataGridView1.Rows.Insert(hit.RowIndex, e.Data.GetData(typeof(Objects.Amazon.PoDetail)));
        }
        else
        {
            dataGridView1.Rows.Add(e.Data.GetData(typeof(Objects.Amazon.PoDetail)));
        }
    }

显然,它在e.Data.GetData失败,因为它从子窗体中的当前datagridview获取数据。

我想不出在表单之间传递数据的方法。

1 个答案:

答案 0 :(得分:1)

如何做到这一点。 dragdrop数据与您在DoDragDrop方法中传递的类型相同。因此它是 DataGridViewRow 类型。那应该是 -

object dropData = e.Data.GetData(typeof(DataGridViewRow));