How to drag information from a DataGridView control

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.

你可能感兴趣的:(datagridview)