Skip to main content
 首页 » 编程设计

c#之拖放在 C# 中不起作用

2024年02月23日14mengfanrong

我想出了如何在 how to drag gridview row from one grid to another 的数据 GridView 之间拖动行,但现在我遇到了问题。我可以将行从 gridPODetails 拖到 DataGridView1。我可以将该行从 DataGridView1 拖回 gridPODetails。但在那之后我什么也得不到。我希望能够无限期地来回拖,但我只能去那里和来回。是什么导致了这种情况以及如何纠正?

 private void gridPODetails_MouseDown(object sender, MouseEventArgs e) 
        { 
            DataGridView.HitTestInfo info = gridPODetails.HitTest(e.X, e.Y); 
 
            if (info.RowIndex >= 0) 
            { 
                DataRow view = ((DataTable)(gridPODetails.DataSource)).Rows[info.RowIndex]; 
                if (view != null) 
                { 
                    gridPODetails.DoDragDrop(view, DragDropEffects.Copy); 
                } 
            } 
        } 
 
        private void gridPODetails_DragEnter(object sender, DragEventArgs e) 
        { 
            e.Effect = DragDropEffects.Copy; 
        } 
 
        private void gridPODetails_DragDrop(object sender, DragEventArgs e) 
        { 
            DataGridView grid = sender as DataGridView; 
            DataTable table = grid.DataSource as DataTable; 
            DataRow row = e.Data.GetData(typeof(DataRow)) as DataRow; 
 
            if (row != null && table != null && row.Table != table) 
            { 
                table.ImportRow(row); 
                row.Delete(); 
            } 
        } 
 
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e) 
        { 
            DataGridView.HitTestInfo info = dataGridView1.HitTest(e.X, e.Y); 
 
            if (info.RowIndex >= 0) 
            { 
                DataRow view = ((DataTable)(dataGridView1.DataSource)).Rows[info.RowIndex]; 
                if (view != null) 
                { 
                    dataGridView1.DoDragDrop(view, DragDropEffects.Copy); 
                } 
            } 
        } 
 
        private void dataGridView1_DragEnter(object sender, DragEventArgs e) 
        { 
            e.Effect = DragDropEffects.Copy; 
        } 
 
        private void dataGridView1_DragDrop(object sender, DragEventArgs e) 
        { 
            DataGridView grid = sender as DataGridView; 
            DataTable table = grid.DataSource as DataTable; 
            DataRow row = e.Data.GetData(typeof(DataRow)) as DataRow; 
 
            if (row != null && table != null && row.Table != table) 
            { 
                table.ImportRow(row); 
                row.Delete(); 
            } 
        } 

请您参考如下方法:

在 row.Delete() 之后添加 table.AcceptChanges() 应该允许您在表之间向后移动行。

这样做的原因可能是因为导入以前删除的行会导致问题。