Windows Develop Bookmark and Share   
 index > Windows Forms General > Implement Drag and Drop in DataGridView
 

Implement Drag and Drop in DataGridView

Hi
I have a data grid view in which 10 columns are there. There is a column named as Order. that Order column takes values from 1 to 10. Means if there are 10 rows then col order starts from 1 to 10.

Now i wnat that to grag any row to any position and then sort. Means selcct the row which has Order 5 amove it to 1. So now the 1 st row wuill contain the values of 5th row and the the 5th row qill contain the values of 1...

how can i do this.
Progress2007  Saturday, April 18, 2009 1:11 PM
Hi Progress2007,

Actually, when the first row was moved to the fifth row, we can first save the fifth row, and move it to the first row. The datagridview doesn't have built-in drag-drop functionality, but we can achieve the goal by ourselves. Please refer to the Sample code in the DataBinding FAQ .

I've added something based on the code in the DataBinding FAQ, now the following sample can totally achieve your goal.

public partial class Form1 : Form
    {
        private int rowIndexFromMouseDown;
        private Rectangle dragBoxFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;
        public Form1()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
            this.dataGridView1.AllowDrop = true;
           
            
        }

        void Form1_Load(object sender, EventArgs e)
        {
            IntializeDataGrid();     
            this.dataGridView1.MouseDown+=new MouseEventHandler(dataGridView1_MouseDown);
            this.dataGridView1.DragOver += new DragEventHandler(dataGridView1_DragOver);
            this.dataGridView1.DragDrop += new DragEventHandler(dataGridView1_DragDrop);
            this.dataGridView1.MouseMove += new MouseEventHandler(dataGridView1_MouseMove);
        }

        void dataGridView1_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {

                // If the mouse moves outside the rectangle, start the drag.

                if (dragBoxFromMouseDown != Rectangle.Empty &&

                    !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {



                    // Proceed with the drag and drop, passing in the list item.                   

                    DragDropEffects dropEffect = dataGridView1.DoDragDrop(

                    dataGridView1.Rows[rowIndexFromMouseDown],

                    DragDropEffects.Move);

                }

            }
        }

        void dataGridView1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            // 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));



            // Get the row index of the item the mouse is below.

            rowIndexOfItemUnderMouseToDrop =

                dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

            DataGridViewRow row = this.dataGridView1.Rows[rowIndexOfItemUnderMouseToDrop];
        
            
            // 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;
                int rowToMoveIndex = rowToMove.Index;

                dataGridView1.Rows.RemoveAt(rowIndexFromMouseDown);

                dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

                dataGridView1.Rows.RemoveAt(rowIndexOfItemUnderMouseToDrop-1);
                dataGridView1.Rows.Insert(rowToMoveIndex, row);
                
            }
        }




        void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            // Get the index of the item the mouse is below.

            rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
            if (rowIndexFromMouseDown != -1)
            {

                // Remember the point where the mouse down occurred.

                // The DragSize indicates the size that the mouse can move

                // before a drag event should be started.               

                Size dragSize = SystemInformation.DragSize;



                // Create a rectangle using the DragSize, with the mouse position being

                // at the center of the rectangle.

                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),

                                                               e.Y - (dragSize.Height / 2)),

                                    dragSize);

            }

            else

                // Reset the rectangle if the mouse is not over an item in the ListBox.

                dragBoxFromMouseDown = Rectangle.Empty;
        }

        private void IntializeDataGrid()
        {
            this.dataGridView1.Columns.Add("AA", "AA");
            this.dataGridView1.Columns.Add("Order", "BB");
            this.dataGridView1.Rows.Add("a", "1");
            this.dataGridView1.Rows.Add("a", "2");

            this.dataGridView1.Rows.Add("a", "3");
            this.dataGridView1.Rows.Add("a", "4");
            this.dataGridView1.Rows.Add("a", "5");
            this.dataGridView1.Rows.Add("a", "6");

            this.dataGridView1.Rows.Add("a", "7");
            this.dataGridView1.Rows.Add("a", "8");
            this.dataGridView1.Rows.Add("a", "9");
            this.dataGridView1.Rows.Add("a", "10");
        }
       
    }

If you have any further problem, please feel free to let me know.



Best regards,
Bruce Zhou
Please mark the replies as answers if they help and unmark if they don't.
Bruce.Zhou  Monday, April 20, 2009 3:47 PM
Hi Progress2007,

Actually, when the first row was moved to the fifth row, we can first save the fifth row, and move it to the first row. The datagridview doesn't have built-in drag-drop functionality, but we can achieve the goal by ourselves. Please refer to the Sample code in the DataBinding FAQ .

I've added something based on the code in the DataBinding FAQ, now the following sample can totally achieve your goal.

public partial class Form1 : Form
    {
        private int rowIndexFromMouseDown;
        private Rectangle dragBoxFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;
        public Form1()
        {
            InitializeComponent();
            this.Load += new EventHandler(Form1_Load);
            this.dataGridView1.AllowDrop = true;
           
            
        }

        void Form1_Load(object sender, EventArgs e)
        {
            IntializeDataGrid();     
            this.dataGridView1.MouseDown+=new MouseEventHandler(dataGridView1_MouseDown);
            this.dataGridView1.DragOver += new DragEventHandler(dataGridView1_DragOver);
            this.dataGridView1.DragDrop += new DragEventHandler(dataGridView1_DragDrop);
            this.dataGridView1.MouseMove += new MouseEventHandler(dataGridView1_MouseMove);
        }

        void dataGridView1_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {

                // If the mouse moves outside the rectangle, start the drag.

                if (dragBoxFromMouseDown != Rectangle.Empty &&

                    !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {



                    // Proceed with the drag and drop, passing in the list item.                   

                    DragDropEffects dropEffect = dataGridView1.DoDragDrop(

                    dataGridView1.Rows[rowIndexFromMouseDown],

                    DragDropEffects.Move);

                }

            }
        }

        void dataGridView1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            // 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));



            // Get the row index of the item the mouse is below.

            rowIndexOfItemUnderMouseToDrop =

                dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;

            DataGridViewRow row = this.dataGridView1.Rows[rowIndexOfItemUnderMouseToDrop];
        
            
            // 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;
                int rowToMoveIndex = rowToMove.Index;

                dataGridView1.Rows.RemoveAt(rowIndexFromMouseDown);

                dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rowToMove);

                dataGridView1.Rows.RemoveAt(rowIndexOfItemUnderMouseToDrop-1);
                dataGridView1.Rows.Insert(rowToMoveIndex, row);
                
            }
        }




        void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            // Get the index of the item the mouse is below.

            rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;
            if (rowIndexFromMouseDown != -1)
            {

                // Remember the point where the mouse down occurred.

                // The DragSize indicates the size that the mouse can move

                // before a drag event should be started.               

                Size dragSize = SystemInformation.DragSize;



                // Create a rectangle using the DragSize, with the mouse position being

                // at the center of the rectangle.

                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),

                                                               e.Y - (dragSize.Height / 2)),

                                    dragSize);

            }

            else

                // Reset the rectangle if the mouse is not over an item in the ListBox.

                dragBoxFromMouseDown = Rectangle.Empty;
        }

        private void IntializeDataGrid()
        {
            this.dataGridView1.Columns.Add("AA", "AA");
            this.dataGridView1.Columns.Add("Order", "BB");
            this.dataGridView1.Rows.Add("a", "1");
            this.dataGridView1.Rows.Add("a", "2");

            this.dataGridView1.Rows.Add("a", "3");
            this.dataGridView1.Rows.Add("a", "4");
            this.dataGridView1.Rows.Add("a", "5");
            this.dataGridView1.Rows.Add("a", "6");

            this.dataGridView1.Rows.Add("a", "7");
            this.dataGridView1.Rows.Add("a", "8");
            this.dataGridView1.Rows.Add("a", "9");
            this.dataGridView1.Rows.Add("a", "10");
        }
       
    }

If you have any further problem, please feel free to let me know.



Best regards,
Bruce Zhou
Please mark the replies as answers if they help and unmark if they don't.
Bruce.Zhou  Monday, April 20, 2009 3:47 PM

You can use google to search for other answers

Custom Search

More Threads

• How to Invoke SendMessage
• How to remove close button from messagebox
• DataGridView custom column property editor
• issues while painting lines on the back of a textbox!
• Derived Control child docking
• Access key behaviour
• Programmatically loading comboBox and selecting the value.
• Adding controls in windows datagrid
• Shortcut Keys :)
• Calling thread in class files