Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Drag and Drop Text from One to Other Datagrirdview in C# Windows Application

4.67/5 (7 votes)
18 Feb 2010CPOL1 min read 53.4K   3.5K  
This example will show how to drag data from one datagridview to another

Introduction

This is my first article and I going to explain how we can copy or move data from one datagrid view to another using Drag N Drop feature.

Background

AFTER reading lots of articles on various sites, I got to know that it's easy to add a row or column to DataGridView control using dragdrop. But there is a problem when we have to add data to a single cell because during drag of data we are unable to get cells rowIndex and ColumnIndex. So we have to determine using the X and Y coordinates returned by the mouse pointer.

Using the Code

There are only three main events that you have to handle.

  1. CellMouseDown for the DataGridView (dataGridView2 in my case) from which data is copied. We write the following code:
    C#
    private void dataGridView2_CellMouseDown
       (object sender, DataGridViewCellMouseEventArgs e)
    {
     dataGridView2.DoDragDrop(dataGridView2.Rows
       [e.RowIndex].Cells[e.ColumnIndex].Value.ToString(),
    DragDropEffects.Copy);
    
    }
    
  2. DragEnter event of the DataGridView (dataGridView1 in my case) in which data is to be pasted.
    C#
    private void dataGridView1_DragEnter(object sender, DragEventArgs e)
            {
                if (e.Data.GetDataPresent(typeof(System.String)))
                    e.Effect = DragDropEffects.Copy;
                else
                    e.Effect = DragDropEffects.None;
            } 
  3. Finally DragDrop event of the DataGridView (dataGridView1 in my case) in which data is to be pasted.
    C#
    private void dataGridView1_DragDrop(object sender, DragEventArgs e) {
     if (e.Data.GetDataPresent(typeof(System.String)))
     {
     Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));               
     dataGridView1.Rows[dataGridView1.HitTest(clientPoint.X, 
    	clientPoint.Y).RowIndex].Cells[dataGridView1.HitTest(clientPoint.X,
     clientPoint.Y).ColumnIndex].Value = 
    	(System.String)e.Data.GetData(typeof(System.String));  
      }                       
    }

Similarly, you can use drag and drop for other controls as well.
I hope it will help you.

Happy coding!!!!!!!!!!!!!

Best of luck.

History

  • 18th February, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)