Click here to Skip to main content
15,878,945 members
Articles / Programming Languages / C#

Drag and Move rows in DataGridView Control

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
26 Aug 2014CPOL2 min read 67.8K   13   2
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

C++
int rowIndexFromMouseDown ;
DataGridViewRow rw;

Will Defining Data on page load event.

C++
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.

C++
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.

C++
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.

C++
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)


Written By
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

 
QuestionAn unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Pin
LuQman Asif14-Jul-21 9:42
LuQman Asif14-Jul-21 9:42 
QuestionA warning about DragDrop event handlers Pin
Alan N26-Aug-14 4:05
Alan N26-Aug-14 4:05 

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

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