我还在学习C#,所以我希望有人可以帮助我。
我有两个DataGridView
个对象,当我从datagridview1拖放时,它可以工作,但如果我再次从datagridview1拖动到2,则数据会覆盖第一列的值。每次重复都会创建一个额外的空白列,其中包含来自datagridview1的列名,但不会将值复制到其各自的列中。所有值都将位于第一列。
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
List<int> selectedColumns = new List<int>();
// The mouse locations are relative to the screen, so they must be
// converted to client coordinates.
Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
dataGridView1.DataBindings.Clear();
// Get the row index of the item the mouse is below.
rowIndexOfItemUnderMouseToDrop = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
// If the drag operation was a move then remove and insert the row.
if (e.Effect == DragDropEffects.Move)
{
DataGridViewRow rowToMove = e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;
listBox1.Items.Add(rowIndexOfItemUnderMouseToDrop.ToString());
listBox1.Items.Add(columIndexFromMouseDown.ToString());
// dataGridView1.Rows.RemoveAt(rowIndexFromMouseDown);
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
if (col.Index == columIndexFromMouseDown)
{
dataGridView2.Columns.Add((DataGridViewColumn)col.Clone());
selectedColumns.Add(columIndexFromMouseDown);
}
}
int rowIndex = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
dataGridView2.Rows.Add();
for (int i = 0; i < selectedColumns.Count; i++)
{
dataGridView2.Rows[rowIndex].Cells[i].Value = row.Cells[selectedColumns[i]].Value;
}
rowIndex++;
}
// dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);
}
// dataGridView1.DataSource = DataSetRecords.Tables[0];
}
附件是代码。
有什么想法吗?提前致谢。