我最近试图找到一些代码来从一个数据网格视图中拖放一行到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);
}
}
1 回答
将datagridview2的AllowDrop属性设置为false .