REL = "stylesheet" type = text / css href = "http://www.codeproject.com/styles/global.css">
Link from: http://www.codeproject.com/cs/misctrl/elvindataGridEx.asp
Introduction
DataGrid is one of the most powerful Windows? Forms control. By using default DataGrid property settings you can easily bind a DataSet to it to create an impressive Windows Forms user interface? One that display large amounts of data efficiently and intuitively without bewildering the user.
Thanks to the extensible architecture of DataGrid control, it gives developers the flexibility in hand to extend its functionalities, where native support is not sufficed. In this article, I am going to show you how to enhance the DataGrid control with the drag and drop support .
Background
In this implementation, I've made use of some unmanaged Win32 APIs to perform the graphics drawing process? One that draw the semi-transparent dragged column during the drag and drop operation. All these Win32 APIs are encapsulated in the WinGDI.cs file for .
BitBlt? Bit Block Transfer, one of the powerful drawing functions which transfer a block of bits (a bitmap) from one device context to another.. One point worth mentioning in this API is that currently there are 17 constants defined for the dwRop (Raster Operation code) variable and you can easily create different kind of effects on image by changing the raster operation code. SRCCOPY (0xcc0020) is the easiest to use and performs a simple copy action. [DllImport ( "gdi32.dll")]
Public Static Extern Bool Bitblt
(
INTPTR HDCDEST, // Handle To Destination DC (Device Context)
INT NXDEST, // X-Coord of Destination Upper-Left Corner
INT NYDEST, // Y-Coord of Destination Upper-Left Corner
Int nwidth, // width of destination rectangle
Int nheight, // HEIGHT OF Destination Rectangle
INTPTR HDCSRC, // Handle To Source DC
Int nxsrc, // x-coordinate of source Upper-Left Corner
INT NYSRC, // Y-Coordinate of Source Upper-Left Corner
System.Int32 DWrop // Raster Operation Code
);
For more information on this API, please consult the win32 documentation.
USING THE CODE
To preserve the existing functionalities provided by DataGrid control, I Ni e created a new control named DataGridEx, which inherits from the existing DataGrid control. A property AllowUserToOrderColumns is added, which enables or disables the control Zha ability to reorder the columns. In order to Provide Drag and Drop for Column Reordering, The Methods OnMousedown, OnMousemove and ONMOUSEUP OF THE BASE CONTROL MUST BE OVERRIDEN.
OnMouseDown is the method that will be called when column header is clicked. To initiate the drag operation, it entails the AllowUserToOrderColumns property has been set to true and the mouse button that initiates the click event must be left mouse button. Just before starting the drag operation, ColumnStartDrag event will be fired to determine whether this column is drag-able. Developers at the application level can react to this event by setting the Cancel variable in the event arguments to true to stop the drag operation. It everything goes fine, the Process of Drag Operation Starts.Protected Override Void OnMouseDown (System.Windows.Forms.MouseEventArgs E)
{
Try
{
DataGrid.hittestinfo HTI = Hittest (E.x, E.Y);
/ *
* The Following Conditions Must Be Met in Order To
* START of the DRAG OPERATION
* 1) Column header is copy with left mouse button.
* 2) AllowUsertoordercolumns Property Has Been Set To True
*
* * /
IF
(hti.type == DataGrid.hittesttype.columnhead)
&& ((E.Button & Mousebuttons.left) == MouseButtons.Left)
&& (allowcolumnReorder))
{
// Notify Application That The Drag Operation Is About To Start
ColumnStartDrageventargs CSDE = New ColumnStartDrageventargs
HTI.COLUMN, GETCOLUMNNAME (HTI.COLUMN), FALSE
OncolumnStartDrag (CSDE);
IF (! csde.cancel) // this column is drag-able
{
// Remember the column header clicked
DragcolumnIndex = hti.column;
ISCOLUMNDRAGGING = True;
/ *
* Currently, There is no way to determine the Drag Column's top
* Left position.
* Workaround: Assumes the mouse copy in the middl of the
* DRAG column.
*
* * /
MouseDelta = New Point
(
E.X - (E.x - (getColumnwidth / 2),
(CaptionVisible == True? GetcaptionHeight (): 0));
Point Dragcolumn = PointToscreen (New Point (E.x, MouseDelta.);
Point ScreenPoint = PointToscreen (New Point (E.x, E.Y));
ScreenPoint.x - = mousedelta.x;
ScreenPoint.y = DragColumn.y;
// Retrieve The DataGridColumnStyle for the Drag Column
DragcolumnStyle = getColumnStyle (HTI.COLUMN);
// Create the screen graphic Device
CreatedIndisplayDC ();
// determine the actual size of the dragged image
Dragimagesize = New size (DragcolumnStyle.width,
ColumnHeaderheight - 2);
// determine and create the Image buffer.
Buffer = new bitmap (math.max (DragcolumnStyle.width,
NODROPIMAGE_WIDTH 2), ColumnHeaderHeight;
Buffergraphics = graphics.fromImage (buffer);
PBufferdc = buffergraphics.getHDC ();
// Copy The Rectangluar Image From The Screen Into Buffer.
Wingdi.bitblt (Pbufferdc, 0, 0, Buffer.Width, Buffer.Height,
PDisPlayDC, ScreenPoint.x, ScreenPoint.y, Wingdi.Srccopy;
// store the image buffer position for tracking
Bufferpos = New Point (ScreenPoint.x, ScreenPoint.y);
}
}
}
Catch (exception) {/ * ignore * /}
Finally
{
Base.onmousedown (e);
}
}
}
OnMouseMove method will be called to draw the semi-transparent dragged column as the mouse moving around in the DataGrid. If the dragged column is drag over to another column, ColumnSequenceChanging event will be fired to determine whether the dragged column can be dropped onto it. Developers at the application level can use this event to determine the droppable columns based on their condition. An X icon will be drawn on the dragged column to inform users that the particular column is not droppable.
Protected Override Void OnmouseMove (MouseEventArgs E)
{
Try {
DataGrid.hittestinfo HTI = Hittest (E.x, E.Y);
/ *
* The Following Conditions Must Be Met Before
* Performing The Drawing of Drag Operation
* 1) AllowusertoorderColumns Property Has Been Set To True
* 2) Column is being Dragged with left mouse button
*
* * /
IF
(AllowColumnReorder)
&& (iscolumndragging)
&& ((E.Button & MouseButtons.Left) == MouseButtons.Left)))
{
IF (hti.column> = 0)
{
// RE-Calculate the mouse location in the screen
Point ScreenPoint = PointToscreen (New Point (E.x, E.Y));
ScreenPoint.x - = mousedelta.x;
ScreenPoint.y = bufferpos.y;
// performs the image swapping
Wingdi.bitblt (pdisplaydc, bufferpos.x, bufferpos.y,
Buffer.Width, Buffer.height, PbufferDC, 0,
0, wingdi.srccopy;
Wingdi.bitblt (Pbufferdc, 0, 0, Buffer.Width, Buffer.Height,
PdisplayDC, ScreenPoint.x, ScreenPoint.y,
Wingdi.srccopy;
Bufferpos = New Point (ScreenPoint.x, ScreenPoint.y);
/ *
* Notify Application That The Dragged Column Is Dragging Over
* To Another Column and Dermines WHether The Dragged Column
* Can Be Dropped ONTO IT.
*
* * /
ColumnsequenceChangingEventArgs CSCE =
New columnsequerncechangingEventArgs (DragColumnIndex,
GetColumnName (DragcolumnIndex), HTI.COLUMN,
GetColumnName (HTI.COLUMN), FALSE
OncolumnsequernCechanging (CSCE);
IF (csce.cancel) // Drop on this column is not allow
DrawDragImage (DisplayGraphics, ScreenPoint.x, ScreenPoint.y, False);
Else
DrawDragImage (DisplayGraphics, ScreenPoint.x, ScreenPoint.y, true);
}
}
}
Catch (exception) {/ * ignore * /}
Finally
{
Base.onmousemove (e);
}
}
}
When the mouse button releases, OnMouseUp method will be called to invoke the MoveColumn function to reorder the columns if the dragged and dropped column is not the same. ColumnSequenceChanged event will be fired once the column reordering is done. This marks the end of the drag Operation and performs the next, keeping.protected Override void onmouseup (System.Windows.Forms.MouseEventArgs E)
{
Try
{
DataGrid.hittestinfo HTI = Hittest (E.x, E.Y);
IF
(AllowColumnReorder)
&& (iscolumndragging)
&& ((E.Button & MouseButtons.Left) == MouseButtons.Left)))
{
// clean up The Drawn Image from the screen
Wingdi.bitblt (pdisplaydc, bufferpos.x, bufferpos.y, buffer.width,
Buffer.height, PBufferDC, 0, 0, Wingdi.Srccopy;
/ *
* The Following Conditions Must Be Met Before Moving The Drag Column
* 1) Drop Column is within bound
* 2) Source Column <> Destination Column
* * /
IF (hti.column> = 0 && DragColumnIndex! = hti.column)
{
/ *
* Notify Application That The Dragged Column Is About To Drop ONTO
* another column.
* * /
ColumnsequenceChangingEventArgs columnChanging =
New columnsequerncechangingEventArgs (DragColumnIndex,
GetColumnName (DragcolumnIndex), HTI.COLUMN,
GetColumnName (HTI.COLUMN), FALSE
Oncolumnsequerncechanging (columnChanging);
IF (! columnChanging.cancel) // Drop on this column is allowed
{
//Move the column
MoveColumn (DragColumnIndex, HTI.COLUMN);
// Notify Application That Dragged Column
// is reordered to new location
ColumnsequenceChangeDeventArgs columnChanged =
New ColumnsequerncechangeDeventArgs (ColumnChangeing.SourceColumnIndex,
ColumnChanging.sourceColumnName, ColumnChanging.DestinationColumnIndex,
ColumnChanging.DestinationColumnName; oncolumnsequenceChanged (ColumnChanged);
}
}
// House Keeping
ISCOLUMNDRAGGING = FALSE;
DragcolumnIndex = -1;
DragcolumnStyle = NULL;
DisposedDisplayDC ();
Disposebufferdc ();
}
}
Catch (exception) {/ * ignore * /}
Finally
{
Base.onmouseUp (e);
}
}
The cornerstone of drawing the dragged column is encapsulated in the function DrawDragImage. A normal semi-transparent dragged column will be drawn when it drags over to those droppable columns. Otherwise, a semi-transparent dragged column with an X icon will be drawn.
Private Void Drawdragimage (Graphics G, Int X, Int Y, Bool Benable)
{
Try
{
g.smoothingmode = smoothingmode.antialias;
// ant-aliased rendering
Rectangle Rect = New Rectangle (X, Y, Dragimagesize.width,
Dragimagesize.height);
Using (Pen P = new pen (color.ble))
{
// Semi-Transparent
Using (Brush Backbrush = New Solidbrush (Color.Fromargb (127,
Color.lightsteelblue))))))))))))))
{
Using (Brush Forebrush = New Solidbrush (Color.Black))
{
G.FillRectangle (Backbrush, Rect.Left 1, Rect.top 1,
Rect.width - 2, Rect.Height - 2);
g.drawRectangle (p, rest.left, rest.top, rect.width - 1,
Rect.height - 1);
Using (StringFormat sf = new stringformat (stringformatflags.11))
{
Sf.LineAlignment = stringalignment.center;
IF (DragColumnStyle.Alignment) == horizontalalignment.ceter)
Sf.Alignment = stringalignment.center;
Else IF (DragcolumnStyle.Alignment == horizontalalignment.Left)
sf.alignment = stringalignment.near;
Else IF (DragColumnStyle.Alignment == horizontalalignment.right)
sf.alignment = stringalignment.far;
g.drawstring (DragcolumnStyle.Headertext, Headerfont,
Forebrush, RECT, SF);
// Draw an x icon in the semi-transparent Drag Column
IF (! BENABLED)
{
Using (Pen Redpen = new Pen (New Solidbrush, 3))
{
// Note: Those Offset Applied Here Is Meant To
// Avoid Drawing the x icon outside
// of the bound reccTangle.
Point p1; point p2; // x
Point P3; Point P4; // Y
IF (Dragimagesize.width> NodropImage_width)
{
INT LEFT = Rect.Left (Dragimagesize.width
- NODROPIMAGE_WIDTH) / 2);
P1 = new point (left, rect.top 1);
P2 = new point_Width, Rect.top
Buffer.Height - 2);
P3 = New Point (Left Nodropimage_Width, Rect.top 1);
P4 = New Point (Left, Rect.top Buffer.Height - 2);
}
Else
{
P1 = New Point (Rect.Left 1, Rect.top 1);
P2 = new point (Rect.Left NodropImage_width - 1,
Rect.top Buffer.Height - 2);
P3 = new point (Rect.Left NodropImage_width - 1,
Rect.top 1);
P4 = new point (Rect.Left 1, Rect.top Buffer.Height - 2);
}
Redpen.startcap = linecap.Round;
Redpen.endcap = linecap.Round;
g.drawline (redpen, p1, p2);
g.drawline (redpen, p3, p4);
}
}
}
}
}
}
Catch (exception) {/ * ignore * /}
}
MoveColumn performs the intelligent column reordering where dragged column will be positioned before the dropped column if the dragged column was previously positioned after the dropped column and vice versa.
Public void MoveColumn (int fromcolumn, int trackumn)
{
IF (fromColumn == TOCOLUMN) RETURN
DataGridTableStyle Oldts = Tablestyles [0];
DataGridTablestyle newts = new dataGridtablelectyle ();
NEWTS.MAPPINGNAME = Oldts.mappingname; // Table Name
CopyTableStyle (Oldts, Newts);
// Copy the old tablestyle to new tablesterfor (int i = 0; i { IF (i! = fromcolumn && fromcolumn NEWTS.GRIDCOLUMNSTYLES.ADD (Oldts.GridColumnStyles [i]); IF (i == TOCOLUMN) NEWTS.GRIDCOLUMNSTYLES.ADD (Oldts.GridColumnStyles [fromColumn]); IF (i! = fromcolumn&folumn> Tocolumn) NEWTS.GRIDCOLUMNSTYLES.ADD (Oldts.GridColumnStyles [i]); } TableStyles.Remove (Oldts); TableStyles.Add (NewTS); } Points of interest For those developers who are interested to convert the drawing functions from unmanaged code to managed code, feel free to try the DrawImage managed API. However, the performance of DrawImage function is slower than the Win32 counterpart, as it creates and destroys new device context for Each Call. Conclusion Column Reordering is just one enhancement to the DataGrid control. If the native functionalities provided in the Windows Forms controls are not exactly what you need for all your scenarios, you can take advantage of the extensibility features of Windows Forms architecture to override and extend these Controls to make the name..