1

I am still learning C#, so I hope someone could help me with this.

I have two DataGridView objects, when I drag and drop the from datagridview1, it works, but if I drag again from datagridview1 to 2, the data overrides the value from first column. Each repetition will create one additional blank column with the columnname from datagridview1, but will not replicate the values to its respective columns, All the values will be at the first column.

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];
    }

Attached is the code.

Any ideas? Thanks in advance.

4

0 回答 0