Click here to Skip to main content
6,928,573 members and growing! (17,580 online)
Email Password   helpLost your password?
Languages » C / C++ Language » General     Intermediate

How to drag information from a DataGridView control

By renzea

Sample code that shows how to drag bound information from the DataGridView control to another control (i.e. ListBox).
C#, Windows, .NET, Visual-Studio, Dev
Posted:28 Dec 2005
Views:92,918
Bookmarked:66 times
printPrint Friendly   add Share
      Discuss Discuss   Broken Article?Report  
20 votes for this article.
Popularity: 5.18 Rating: 3.98 out of 5
3 votes, 15.0%
1

2
2 votes, 10.0%
3
6 votes, 30.0%
4
9 votes, 45.0%
5

Introduction

While doing some recent home-work, I needed to figure out how to implement drag-and-drop from a DataGridView control. I had two main controls on the form: a ListBox that contained a list of categories, and a DataGridView control that contained a list of products associated with that category. To keep things simple, I wanted to be able to drag a product from the Grid to the ListBox to change a product's category.

Starting the Drag-and-Drop

The first thing I did was to attach an event handler to the DataGridView's MouseDown event. Because the DataGridView monopolizes the left mouse button, and it is very efficient at performing updates, inserts, and deletes, I decided to use the right mouse button for drag-and-dropping. I didn't need context menus. (Otherwise, I would have considering RMB + Alt/Shift/Ctrl clicking).

void grdCampaigns_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
      DataGridView.HitTestInfo info = grdCampaigns.HitTest(e.X, e.Y);
      if (info.RowIndex >= 0)
      {
        DataRowView view = (DataRowView)
               grdCampaigns.Rows[info.RowIndex].DataBoundItem;
        if (view != null)
          grdCampaigns.DoDragDrop(view, DragDropEffects.Copy);
    }
  }
}

The code tests for the right mouse Button. If the RMB was pressed, I performed a HitTest using the x and y components of the MouseEventArgs. Because the RMB does not natively interact with the DataGridView, clicking the RMB will not select a row. If the user clicks the fourth row, and the first row was selected (from before), they will unwittingly drag the first row, rather than the fourth row. It was not intuitive at all.

So I used the information returned by HitTest to ensure I was working with the row and the column under the mouse pointer, rather than the previously selected row, which made the program much more intuitive.

After checking to make sure the data was valid, I passed the DataRowView into the DoDragDrop event, which started the drag-and-drop operation.

Preparing for the Drop

All the above preparation is useless without having a target to drop the information in. To that end, you need to prepare a drop target. If you are working with standard data types, this may not be necessary. Some support may be there already. This is especially true of strings. For more complex data types, however, such as a DataRowView (with which I was working), you will need to provide the plumbing yourself.

This is actually rather easy. First, you need to tell the target it is available for drag-and-drop operations. This is done by setting the AllowDrop property of most controls to true. Secondly, you need to add code to the DragEnter event of the control.

void lstCategories_DragEnter(object sender, DragEventArgs e)
{
  e.Effect = DragDropEffects.Copy;
}

You can use whatever effect you want, but it should match the effect you used in the DoDragDrop method called earlier, when starting the drag. When I tried drag-and-drop without this line of code, it did not work.

Implementing the Drop

The last step is to implement the DragDrop event of the target control, and manipulate the data.

void lstCategories_DragDrop(object sender, DragEventArgs e)
{
  if (e.Data.GetDataPresent(typeof(DataRowView)))
  {
    // Determine which category the item was draged to

    Point p = lstCategories.PointToClient(new Point(e.X,e.Y));
    int index = lstCategories.IndexFromPoint(p);
    if (index >= 0)
    {
      // Get references to the category and campaign

      DataRowView category = (DataRowView)lstCategories.Items[index];
      DataRowView campaign = (DataRowView)
                              e.Data.GetData(typeof(DataRowView));
      // Get the old and new category ids

      int newID = (int)category[0];
      int oldID = (int)campaign[1];
      // Make sure the two do not match

      if (oldID != newID)
      {
        campaign.BeginEdit();
        campaign[1] = newID;
        campaign.EndEdit();
      }
    }
  }
}

The first step I performed in the drag-drop was to ensure the type of data being dropped was the type I expected to receive. This can be done through the GetDataPresent method, which accepts as its parameter a data type, and returns true if that type is present.

Once I was sure I had valid data--or at least the right data type--I got screen coordinates where the DragDrop operation ended. Like the DataGridView control before it, I had no idea where the data was going. The user could drag the product on any visible category: I had to figure out which one.

That was accomplished through the IndexFromPoint method. However, documentation on this particular method is very poor, and Microsoft fails to note that you need CLIENT coordinates for this to work, not SCREEN coordinates. So, before you can call IndexFromPoint, you need to convert coordinates from screen to client coordinates using the appropriately named PointToClient method.

Once I determined (and verified) the category, I cast references to data items for both the category and the product (campaign). To save unnecessary processing, I checked to make sure the category was in fact different.

I should point out at this time that I was working with a strongly-typed DataSet, with two tables: Categories and Campaigns. Both contained the column CategoryID; CategoryID is the primary key of Categories, and was used for reference in Campaigns. The ListBox used in the examples was bound to the Categories table in the dataset. Whenever the Categories list selection changed, a DataView of child rows was retrieved from the DataSet, and bound to the DataGridView control.

The significance of this point is that when I edit the CategoryID of the campaign DataRowView in the example above, the associated product listing is removed from the grid, because the CategoryID no longer qualifies the product to be in the grid (it is no longer a child of the current category). When the user clicks on the category to which the product was moved, however, the product will appear in that listing, instead.

All in all, the code performed exactly what I wanted: it was simple, it worked, and it was intuitive for the user. I doubt I could have duplicated the results with less code or time any other way.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

renzea


Member

Occupation: Web Developer
Location: United States United States

Other popular C / C++ Language articles:

 
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 22 of 22 (Total in Forum: 22) (Refresh)FirstPrevNext
GeneralDidn't understand anything ... Source code? Pinmemberzahid7813:00 21 Oct '09  
GeneralDragging multiple items on left mouse PinmemberIan M Spencer14:30 1 Sep '09  
QuestionDraging one column to another datagridview PinmemberPappan0:01 29 May '09  
GeneralI wanted to be able to drag a product from the ListView to the Grid PinmemberNatashasv20:40 14 Jan '09  
GeneralI think this way would be better PinmemberMember 43421425:33 20 Nov '08  
GeneralHas anyone VB.NET version? PinmemberJo Raleigh6:41 12 Nov '08  
GeneralRe: Has anyone VB.NET version? PinmemberMember 31389387:08 3 Sep '09  
GeneralUsability Pinmembermr_lasseter12:01 9 Oct '07  
General.Net 2003 dataGrid component PinmemberN3CAT15:48 3 Jul '07  
GeneralHelp please Pinmembernoha8611:49 13 Jun '07  
GeneralHow u people Resize the rows if we give Mouse button Lef Pinmemberwinheart20:09 3 Apr '07  
GeneralDragging using the left mouse button Pinmemberjjerry831:20 30 Mar '07  
GeneralRe: Dragging using the left mouse button PinmemberName taken1:33 3 Feb '08  
Sorry, but it doesn't work. It has the same problem that any other DataGridView drag&drop code I've seen by now has: The selection is always reduced to the row that was clicked on to start dragging. Dragging multiple selected rows is not possible with it.
GeneralDataGridViewSelectedRows Pinmembercesarsouza15:59 17 Feb '07  
QuestionOne issue about right button Pinmembermicblues20:53 5 Feb '07  
GeneralThanks PinmvpJosh Smith11:55 19 Jan '07  
GeneralRe: Thanks Pinmemberjfdoubell22:31 9 Sep '07  
GeneralSource please.... :( PinmemberNuno Agapito13:05 11 Dec '06  
GeneralVery good example! Pinmemberloizzi16:11 16 Jun '06  
GeneralDatagridview rotate Pinmemberhorvat20:55 9 May '06  
Generalnamespace problem Pinmemberidreesbadshah9:02 30 Jan '06  
GeneralRe: namespace problem Pinmemberrenzea13:59 30 Jan '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 28 Dec 2005
Editor: Smitha Vijayan
Copyright 2005 by renzea
Everything else Copyright © CodeProject, 1999-2010
Web19 | Advertise on the Code Project