查询了许多资料都是单个单元格的替换,而我这边则需要行的拖拽.,我这边记录数据源的行位置,拖拽后则从源数据读取对应的数据添加到目标源中。
例如要实现从gridSource到gridTarget的拖拽,需要一个设置和三个事件:
1、设置gridTarget的属性AllowDrop为True
2、实现gridSource的MouseDown事件,在这里进行要拖拽的Cell内容的保存,保存到剪贴板。
3、实现gridTarget的DragDrop和DragEnter事件,DragDrop事件中的一个难点就是决定拖拽到哪一个Cell
/// <summary>
/// 数据源
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DataGridView.HitTestInfo info = this.dataGridView1.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
{
int currow = info.RowIndex;//记录数据位置,并拷贝
if (currow >-1)
{
this.dataGridView1.DoDragDrop(currow, DragDropEffects.Copy);
}
}
}
}
} /// <summary>
/// 目标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridView2_DragDrop(object sender, DragEventArgs e)
{
if (e.Data != null)
{
int rowindexs = (int)e.Data.GetData(typeof(int));//目标源选择的行位置
DataTable dt = (DataTable)dataGridView1.DataSource;//数据源数据,然后进行对应操作
//操作
}
}
private void DataGridView2_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}多行数据拖拽
/// <summary>
/// 多行数据拖拽(多选拖拽时务必按住ctrl,否则只会拖拽一行)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridViewX1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DataGridView.HitTestInfo info = this.dataGridViewX1.HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
if (info.RowIndex >= 0 && info.ColumnIndex >= 0)
{
int currow = info.RowIndex;//记录数据位置,并拷贝
DataGridViewSelectedRowCollection cs = dataGridViewX1.SelectedRows;
if (currow > -1)
{
this.dataGridViewX1.DoDragDrop(cs, DragDropEffects.Copy);
}
}
}
}
}
/// <summary>
/// 目标
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridView2_DragDrop(object sender, DragEventArgs e)
{
if (e.Data != null)
{
DataGridViewSelectedRowCollection rowindexs = (DataGridViewSelectedRowCollection)e.Data.GetData(typeof(DataGridViewSelectedRowCollection));//目标源选择的行位置
foreach (DataGridViewRow row in rowindexs)//数据获取
{
string value = row.Cells[1].Value.ToString();
}
DataTable dt = (DataTable)dataGridView1.DataSource;//数据源数据,然后进行对应操作
//操作
}
}版权声明:本文为xyy631631原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。