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

ASP.NET - Drag and Drop on a Webpage

By , 28 Dec 2004
 

Introduction

Many web applications are required to be complex yet intuitive to the user. One way to achieve this is to create objects or areas of the web page draggable and droppable. Unfortunately, ASP.NET server controls do not have the Drag events and DragEventArgs. Fortunately, there is a way to enable drag and drop functionalities within a web page. Now keep in mind, this is not like a Windows application where you can drag files from the user's PC to the application. The drag and drop is limited to the boundaries of the web page.

Using the code

  1. Create a web application within your solution.
  2. Create a web page.
  3. Add the provided JavaScript in the <HEAD> of your <HTML>.
  4. Add two textboxes and a button in the web form.
  5. Add the DrawContainers method to the code-behind of the web page.
  6. Ensure that the click event for the button calls the DrawContainers method.

or

  • Download the source code and run the sample application.

JavaScript

This is the JavaScript that enables the drag and drop to take place:

<!--------- Drag and Drop JavaScript ------------>

var TimerID = 0;
var oEl     = null;
var oTarget = null;
var beginDrag = false;
var tmpHTML = "";
  
function killTimer()
{
    if (TimerID != 0 )
    {
        clearTimeout(TimerID);
        TimerID = 0;
    }
}
       
function fnShowDragWindow() 
{
    var obj = document.all("DW");
    
    killTimer();
    
    if (oEl == null)  
    {
        return;
    }
    
    obj.style.top        = oEl.offsetTop;
    obj.style.left        = oEl.offsetLeft;
    obj.style.height    = oEl.offsetHeight - 3;
    obj.style.width        = oEl.offsetWidth - 3;
    obj.innerText        = oEl.SpecimenId;
    obj.style.display    = "block";
    obj.style.zIndex    = 999;
    
    window.document.attachEvent( "onmousemove"  , fnMove );
    window.document.attachEvent( "onscroll"  , fnMove );
    window.document.attachEvent( "onmousemove" , fnCheckState );
    window.document.attachEvent( "onmouseup"    , fnRelease );
    window.document.attachEvent( "onselectstart", fnSelect );
    //window.document.attachEvent("onmouseover",setTarget);
    
    beginDrag = true;
}

function setTarget(id)
{
    var src = document.getElementById(id);
    
    if (src == null) 
    {
        return;
    }
    
    if (src.target == 'true')
    {
        oTarget = src;
    }
    else
    {
        oTarget = null;    
    }
}

function BeginDrag(id)
{
    // Get the item to be dragged.
    oEl = document.getElementById(id);
    
    // Is there an item?
    if(oEl == null)
    {
        return;
    }
    
    tmpHTML = oEl.innerHTML;
    // Set the window timeout.
    TimerID = setTimeout(fnShowDragWindow, 1);
}            


function fnCheckState()
{
    if(event.button != 1)
    {
        fnRelease();
    }
}

function fnSelect()
{
    return false;
}


function fnMove()
{
    if (event.button != 1)
    {
        fnRelease();
        return;
    }
    
    var obj = document.all("DW");
    
    obj.style.top = 
      event.clientY - (obj.offsetHeight/2) + window.document.body.scrollTop;  
    obj.style.left = event.clientX  + window.document.body.scrollLeft;
    window.status = 'Top=' + obj.style.top + ' Left=' + obj.style.left;
    
    if (event.clientY > window.document.body.clientHeight - 10 )
    {
        window.scrollBy(0, 10);
    }
    else if (event.clientY < 10)
    {
        window.scrollBy(event.clientX, -10);
    }
    
}

function fnRelease()
{
    if (beginDrag == false) return;
                           
    window.document.detachEvent( "onmousemove" , fnMove );
    window.document.detachEvent( "onscroll" , fnMove );
    window.document.detachEvent( "onmousemove" , fnCheckState );
    window.document.detachEvent( "onmouseup" , fnRelease );
    window.document.detachEvent( "onselectstart", fnSelect );
    //window.document.detachEvent( "onmouseover", setTarget );
    
    var obj = document.all("DW");
    
    if (oTarget != null) 
    {    
        var targetHTML = oTarget.innerHTML;
        var targetSpecId = oTarget.SpecimenId;
        var sourceSpecId = oEl.SpecimenId;
        
        oEl.innerHTML = targetHTML;
        oEl.SpecimenId = targetSpecId;
        oTarget.SpecimenId = sourceSpecId;
        
        oTarget.innerHTML = tmpHTML;
        
        // Is the container empty?
        if(oTarget.innerHTML != "")
        {
            oTarget.style.backgroundColor="beige";
        }
        else
        {
            oTarget.style.backgroundColor = "turquoise";
        }
        
        if(oEl.innerHTML != "")
        {
            oEl.style.backgroundColor = "beige"
        }
        else
        {
            oEl.style.backgroundColor = "turquoise"
        }
    }
    
    killTimer();
    
    obj.style.display    = "none";
    oEl                    = null;
    oTarget                = null;
    beginDrag            = false;
    TimerID                = 0;
}


function CancelDrag()
{
    if (beginDrag == false)
    {
        killTimer();
    }
}
<!--------- End of Drag and Drop JavaScript ------------>

C# code behind - DrawContainers method

This is the code behind used to create the drag and drop objects:

private void DrawContainers()
{
    TableRowCollection trCol = this.Table1.Rows;
    TableRow tr = null;
    
    // Should we continue?
    if(this.txtContX.Text == null || this.txtContY.Text == null)
        return;
    
    // Size of the row.
    int rowSize = Int32.Parse(this.txtContX.Text); 
    // Number of rows.
    int rowNumber = Int32.Parse(this.txtContY.Text);
    // Total number of containers.
    int numberOfContainers = rowSize * rowNumber;
    // Boolean value for empty table cells.
    bool isEmpty = false;
    
    // Loop through all of the containers.
    for(int i=0; i< numberOfContainers; i++)
    {
        // new row mod.
        int newRow =  i % rowSize;
        
        // Should we create a new row?
        if(tr == null || newRow == 0)
        {
            tr = new TableRow();
            trCol.Add(tr);
        }

        // Empty cell generator.
        if((i+1)%17==0)
        {
            isEmpty = true;
        }
        else
        {
            isEmpty = false;
        }

        // Set the cell collection.
        TableCellCollection tdc = tr.Cells;

        // Create a new table cell.
        TableCell td = new TableCell();
        td.ID = "cell_" + i.ToString();
        
        // Set the cell backcolor.
        td.BackColor = Color.Turquoise;
        // Set the cell's class.
        td.CssClass = "SpecimenLoc";

        td.Attributes.Add("SpecimenId", "");

        // Is the cell empty?
        if(!isEmpty)
        {
            td.Attributes.Add("SpecimenId", i.ToString());
            td.BackColor = Color.Beige;
            td.Text = i.ToString();
        }
        
        // Add javascript attributes to the cell.
        td.Attributes.Add("target", "true");
        td.Attributes.Add("onmousedown", "BeginDrag(this.id);");
        td.Attributes.Add("onmouseup", "CancelDrag();"); 
        td.Attributes.Add("onmouseover", 
                "setTarget(this.id);this.style.cursor='hand';");
        td.Attributes.Add("onmouseout", 
                                "this.style.cursor='default';");
        td.Width = Unit.Pixel(35);
        td.Height = Unit.Pixel(35);

        // Add the cell to the cell collection.
        tdc.Add(td);
    }
}

C# code behind - button click event

The click event of the button:

private void btnDrawContainers_Click(object sender, System.EventArgs e)
{
    // Draw the containers.
    this.DrawContainers();
}

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

Kenny Young
United States United States
Member
Ken currently works as the Director of Software Engineering at the Pediatrics Epidemiology Center at the University of South Florida. He is involved in the architecture and design on numerous clinical trial projects. Some of the project include:
 
1. Rare Diseases Clinical Research Network
2. TrialNet - Diabetes
3. Teddy - Diabetes
4. CCOP - Cancer
5. AIDA - Diabetes

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey9 Feb '12 - 21:13 
Nice
QuestionExplainationmembersakshictr10 Jan '12 - 19:34 
I read this article and tried too but still not able to grasp the complete functionality.Can you explain the functionality like how it works etc., Apart from that i also want drag and drop for image. can you give your suggestion or provide any help.
Keep looking for reply.
Thanks
QuestionNeed some Suggestions.membersupriya_rani2012 Sep '11 - 23:37 
I saw your Article about Drag and Drop On a webpage. It is very nice functionality.
 
I required drag and drop images.Can you please help me regarding this?.i don't know how to implement drag event handler in asp.net.Drag the image from ImageButton and drop it to image Control.I am new to Asp.net.
 
Thanks Advance.
GeneralMy vote of 1memberMember 449609922 Jun '09 - 20:55 
Act
GeneralGood Articlememberkhanjee7730 Dec '08 - 17:30 
A good article a same type of article at
http://khurramjadoononline.blogspot.com/2008/12/aspnet-drag-and-drop.html[^]
GeneralMy vote of 2memberIyigun Cevik8 Dec '08 - 2:47 
firefox?
Generalhii kenny Youngmemberctcalyx6 Aug '07 - 21:06 
We really appreciate ur work
 
we are basically developing web application
 
for clinical trials
 
we are in need of drag and drop feature on our web page in application
 

can we get ur contact number, we want to talk with u
 
my email id is : narasimha.kulkarni@calyxinfo.com
GeneralRe: hii kenny YoungmemberRockrebel7 Aug '08 - 1:42 
hi kenny,
i'm a newbee and i have similar kindda requirement in my project but the script is not working... The error which i'm getting on this statement "obj.style.left = oEl.offsetLeft;" is Object required ... The compiler is not able to comprehend this statement-->
"var obj = document.all("DW");" I've changed document.all by document.getElementbyID as well but its not able to find "DW" ... Kindly let me know is there is any way out ... thanks in advance ...
GeneralRe: hii kenny YoungmemberKenny Young7 Aug '08 - 2:26 
Hi,
 
Have you downloaded the source code? You need to add a DIV to your HTML page that includes the drag and drop javascript. Here is the html you need to add to the body. Look at the SpecStorage.aspx page in the source code.
 
<div class="clsDragWindow" id="DW" align="center" nowrap=""></div>
 
Also, this is an old article. There are some great articles on the web that demonstrate how to do this with AJAX.
 
Hope this helps.
 
Ken
QuestionHyperLinkBitmap Errormemberdiddy4332 Jul '07 - 6:39 
I am getting the following error when trying to run the demo on my machine. Does it matter that we are running ASP.NET 1.1?
 
C:\Inetpub\wwwroot\HyperlinkBitmap\HyperlinkBitmap.cs(13): 'Moffitt.HyperlinkBitmap.HyperlinkBitmap' : cannot inherit from sealed class 'System.Drawing.Bitmap'
 

 
Justin
GeneralDoens't work with firefoxmembercarlintveld31 May '07 - 7:50 
It is a very understanding and interesting demo application, but:
These kinds of web 2.0 functionality have to work with either the ie browser family and with the gecko / mozilla engine.
It has a bug in at least IE7, the drag object isn't positioned correctly, the y-coordinate is 200 pixels off or something.
In Firefox 2 the grey drag object appears but doesn't do anything else at all.
 
So this demo application should be revised conforming the current standards, or else it hasn't a lot of added value.
 
Thanks for your understanding.
 
Carl
GeneralRe: Doens't work with firefoxmembervytas z.16 Aug '07 - 2:33 
I agree - demo is nice, but useless. So I would recommend you stop doing useless stuff and start programming.
 
v
GeneralRe: Doens't work with firefoxmemberbbol19 Nov '07 - 12:49 
Except that this may have been created for a client that mandates that IE is used to run this as an internal application. I wouldn't be so quick to judge there v, just because it is useless to you does not mean that it is useless.
 
B
GeneralDoes n't Work with ASP.Net 2005memberHari Darshan26 Apr '07 - 1:17 
I have upgrade the demo project and found following observation:-
1.It is possible to drag and drop.
2.After press on Button DrawContainer.It shoes previous values only.
3.It seems that this type of Javascript is not supported by .Net Framework 2.0.
4.At IIS level ASP.NET setting is 2.0.
 
CAn you put code for .Net 2005
QuestionHow to get updated row after drag?memberdavihigh12 Sep '06 - 3:29 
What I done is add a button try to iterate all rows in table, and figure out their colors to determine. But I found the Table1.rows number is "0", not "10".
 
So what's happening on?
 
And I have a more question that, is that possible to drag a picture item to another place, and after drop it, post back so that server can handle?
 
Many thanks!
AnswerRe: How to get updated row after drag?memberKenny Young12 Sep '06 - 7:15 
You will need to add client side attributes to the rows such as current index and previous index. In the javascript you will need to set these values accordingly. When a post-back occurs, you must re-order the rows based on the current and previous index values.
 
Thanks,
 
Kenny Young
QuestionCheckbox.memberpy1rdj4 Sep '06 - 11:20 
Thanks for the great code. It has been very useful for me so far. However I wasn't able to make it work with an asp.net checkbox. Is there anything I can do?
 
Thanks.
 
Andre
AnswerRe: Checkbox.memberKenny Young12 Sep '06 - 7:17 
The drag and drop will work with checkboxes. You must set the attributes on the checkboxes that are draggable and droppable.
QuestionDrag n Drop from listbox to a datagridmemberkumarcs4 Sep '06 - 4:11 
This seems to be a gr8 implementation.Thanks to the author.
I have a query.
I need to drag and drop items from listbox to datagrid.
If anybody has implemented please help me out in this.
I tried out but i cant put it in the grid.
 
Thanks
Kumar.
AnswerRe: Drag n Drop from listbox to a datagridmemberKenny Young12 Sep '06 - 7:21 
You can drag an item from the listbox to a grid but you must modify the code from the article.
GeneralDatagrid to Datagrid drag dropmembersandeepautade31 Aug '06 - 2:31 
Hi,
   I want to drag row from one grid to another grid. I have made the changes according to it. And I got success in dragging grid row. But now it dont maintain the viewstate after postback , what can I do for it? Can u suggest anything?
 
Thanks,

 
Sandeep
GeneralRe: Datagrid to Datagrid drag dropmemberKenny Young31 Aug '06 - 2:39 
What is not maintaining the ViewState, the Grid Row's new location? You might have to do some coding on the post-back to remember the new order of the grid row.
GeneralDRAG DROPmemberMon217 Aug '06 - 20:45 
I am wanted to do a drag drop functionality within the ASP.Net Controls. ie: drag items from a ListBox and drop them to TreeView. Is this possible at all. please help me...
 
Manpreet.
 
Manpreet
GeneralRe: DRAG DROPmemberKenny Young31 Aug '06 - 2:37 
Yes, this is possible. Just follow the same instructions the article has and add the parameters to the controls.
Generalmicrosoft treeview [modified]memberazidi13 Jul '06 - 14:37 
im using microsoft treeview ie control ...
can you give how to drag and drop between node and between treeview...
 
-- modified at 20:38 Thursday 13th July, 2006
 
any vb.net code...

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 28 Dec 2004
Article Copyright 2004 by Kenny Young
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid