Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Drag and Move rows in DataGridView Control

, 26 Aug 2014
Rate this:
Please Sign up or sign in to vote.
drag and reorder rows in datagridview control

Introduction

Hello,

I posting a very good article for the users who want to reorder the rows of grid using drag and drop. i design this module for one of my project where the client requires to change the records order display in grid and the will insert into database accordingly and in same order

Background

Before go through with this article , you have to be a knowledge of basic properties and methods of DataGridView.

like

  • how to remove any row
  • how to tranck selected row
  • how to insert row
  • how to get row index of any row.

No issue if you are not aware of any above.

i will go through on all this in brief.

Using the code

First of all will designed our grid either by static data or fetch data from database.

here in this article i am defining the static data.

Firstly we define global declartion of variable which will be used in multiple methods

int rowIndexFromMouseDown ;
DataGridViewRow rw;

Will Defining Data on page load event.

dataGridView1.Columns.Add("name", "Name");
            dataGridView1.Rows.Add(5);
            dataGridView1.Rows[0].Cells[0].Value = "mayank";
            dataGridView1.Rows[1].Cells[0].Value = "rehan";
            dataGridView1.Rows[2].Cells[0].Value = "sandeep";
            dataGridView1.Rows[3].Cells[0].Value = "vijay";
            dataGridView1.Rows[4].Cells[0].Value = "aryan";
            dataGridView1.SelectedRows[0].Selected = false;

In the above code, firstly we create single column and the add 5 rows by calling Add method of rows and then we add five names in five consecutive rows.

Now we select the row to which we have to reorder.

for this we will call the click and select the row.

 private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 1)
            {
                if (e.Button == MouseButtons.Left)
                {                    
                    rw = dataGridView1.SelectedRows[0];
                    rowIndexFromMouseDown = dataGridView1.SelectedRows[0].Index;
                    dataGridView1.DoDragDrop(rw, DragDropEffects.Move);                   
                }
            }
        }

In the above code, we firstly check weather row is selected or not.

I the row is selectedd and user click the left lcick of mouse the track the row and store the row index and add the row for move action in drag drop.

Now , we have selectedd the row.

drag your mouse in grid and for this we enable the move effect of drag and drop.

  private void dataGridView1_DragEnter(object sender, DragEventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                e.Effect = DragDropEffects.Move;
            }
        }

By this, now we have track the row and will move the row and its recorded as tracking.

Now, the final step is to drop the row which we have to reorder.

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            
            int rowIndexOfItemUnderMouseToDrop;
            Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));
            rowIndexOfItemUnderMouseToDrop = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
          
            if (e.Effect == DragDropEffects.Move)
            {
                dataGridView1.Rows.RemoveAt(rowIndexFromMouseDown);
                dataGridView1.Rows.Insert(rowIndexOfItemUnderMouseToDrop, rw);
            }
        }

In the above code,

we finally drop successfully and remove the previous row and add the row to that position by tracking the new row position.

Points of Interest

By this you can give user to adjust rows on their own for better visibility, according to priority and manage their own basis.

License

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

Share

About the Author

Er. Mayank Kothari
Founder Global Infinite Technologies Pvt. Ltd.
India India
I'm a technology lover and when I say technology, I mean the latest, not the old school chalk board types. I love technology and those who know me, know that I'm a '24 hours - technology linked' guy. When i was in class 6th my dad surprised me with a PIII PC whose configuration was 533 MHz + 64 MB + 32 GB and I LOVED IT!!! Since then I started loving 'IT'. (Though, today my nokia lumia 925 has much higher configuration Wink | ;) )
 
some people are born to be an entrepreneur. They employ others rather being employed by others. I'm one of them. With the co-founder, Mr. Nadeem Lohani, I founded my company - Infinite Technologies. After three years of hard work and successfully developing more than 100 applications and websites, now my company is recognized as Global Infinite Technologies Pvt. Ltd. Today, I have a vibrant and enthausiastic team of engineers working towards the goal of the organization and we take care of their development.
 
I want to tell you that I spend my day reading technical articles and making hobbist projects related to computer technology. But, if you've already read the professional page, then trust me - I'm a fun loving person and don't miss any chance to go out with my friends whenever I get some time from computers.

Comments and Discussions

 
QuestionA warning about DragDrop event handlers PinmemberAlan N26-Aug-14 4:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140921.1 | Last Updated 26 Aug 2014
Article Copyright 2014 by Er. Mayank Kothari
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid