Click here to Skip to main content
11,412,516 members (71,470 online)
Click here to Skip to main content

ASP.NET - Drag and Drop on a Webpage

, 28 Dec 2004
Rate this:
Please Sign up or sign in to vote.
Drag and drop contained objects on a webpage.

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:

<!--<span class="code-comment">------- Drag and Drop JavaScript ------------></span>

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 >

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

Share

About the Author

Kenny Young

United States United States
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

Comments and Discussions

 
GeneralMy vote of 5 Pin
manoj kumar choubey at 9-Feb-12 22:13
membermanoj kumar choubey9-Feb-12 22:13 
QuestionExplaination Pin
sakshictr at 10-Jan-12 20:34
membersakshictr10-Jan-12 20:34 
QuestionNeed some Suggestions. Pin
supriya_rani20 at 13-Sep-11 0:37
membersupriya_rani2013-Sep-11 0:37 
GeneralMy vote of 1 Pin
Member 4496099 at 22-Jun-09 21:55
memberMember 449609922-Jun-09 21:55 
GeneralGood Article Pin
khanjee77 at 30-Dec-08 18:30
memberkhanjee7730-Dec-08 18:30 
A good article a same type of article at
http://khurramjadoononline.blogspot.com/2008/12/aspnet-drag-and-drop.html[^]
GeneralMy vote of 2 Pin
Iyigun Cevik at 8-Dec-08 3:47
memberIyigun Cevik8-Dec-08 3:47 
Generalhii kenny Young Pin
ctcalyx at 6-Aug-07 22:06
memberctcalyx6-Aug-07 22:06 
GeneralRe: hii kenny Young Pin
Rockrebel at 7-Aug-08 2:42
memberRockrebel7-Aug-08 2:42 
GeneralRe: hii kenny Young Pin
Kenny Young at 7-Aug-08 3:26
memberKenny Young7-Aug-08 3:26 
QuestionHyperLinkBitmap Error Pin
diddy433 at 2-Jul-07 7:39
memberdiddy4332-Jul-07 7:39 
GeneralDoens't work with firefox Pin
carlintveld at 31-May-07 8:50
membercarlintveld31-May-07 8:50 
GeneralRe: Doens't work with firefox Pin
vytas z. at 16-Aug-07 3:33
membervytas z.16-Aug-07 3:33 
GeneralRe: Doens't work with firefox Pin
bbol at 19-Nov-07 13:49
memberbbol19-Nov-07 13:49 
GeneralDoes n't Work with ASP.Net 2005 Pin
Hari Darshan at 26-Apr-07 2:17
memberHari Darshan26-Apr-07 2:17 
QuestionHow to get updated row after drag? Pin
davihigh at 12-Sep-06 4:29
memberdavihigh12-Sep-06 4:29 
AnswerRe: How to get updated row after drag? Pin
Kenny Young at 12-Sep-06 8:15
memberKenny Young12-Sep-06 8:15 
QuestionCheckbox. Pin
py1rdj at 4-Sep-06 12:20
memberpy1rdj4-Sep-06 12:20 
AnswerRe: Checkbox. Pin
Kenny Young at 12-Sep-06 8:17
memberKenny Young12-Sep-06 8:17 
QuestionDrag n Drop from listbox to a datagrid Pin
kumarcs at 4-Sep-06 5:11
memberkumarcs4-Sep-06 5:11 
AnswerRe: Drag n Drop from listbox to a datagrid Pin
Kenny Young at 12-Sep-06 8:21
memberKenny Young12-Sep-06 8:21 
GeneralDatagrid to Datagrid drag drop Pin
sandeepautade at 31-Aug-06 3:31
membersandeepautade31-Aug-06 3:31 
GeneralRe: Datagrid to Datagrid drag drop Pin
Kenny Young at 31-Aug-06 3:39
memberKenny Young31-Aug-06 3:39 
GeneralDRAG DROP Pin
Mon2 at 17-Aug-06 21:45
memberMon217-Aug-06 21:45 
GeneralRe: DRAG DROP Pin
Kenny Young at 31-Aug-06 3:37
memberKenny Young31-Aug-06 3:37 
Generalmicrosoft treeview [modified] Pin
azidi at 13-Jul-06 15:37
memberazidi13-Jul-06 15:37 
GeneralThe DIV does not move Pin
Sebastian_M at 7-Mar-06 2:07
memberSebastian_M7-Mar-06 2:07 
GeneralRe: The DIV does not move Pin
Sebastian_M at 7-Mar-06 4:07
memberSebastian_M7-Mar-06 4:07 
GeneralRe: The DIV does not move Pin
Saurabhdotnet at 23-Mar-06 2:08
memberSaurabhdotnet23-Mar-06 2:08 
GeneralDrag and Drop from Desktop to Web Page Pin
Allan Holbrook at 15-Feb-06 20:29
memberAllan Holbrook15-Feb-06 20:29 
GeneralRe: Drag and Drop from Desktop to Web Page Pin
Kenny Young at 16-Feb-06 4:10
memberKenny Young16-Feb-06 4:10 
GeneralGreat!!! Pin
pietro77 at 13-Jan-06 6:42
memberpietro7713-Jan-06 6:42 
GeneralMultiple positions Pin
Judd Williams at 28-Sep-05 5:37
memberJudd Williams28-Sep-05 5:37 
Generaltextbox Pin
aleks234 at 3-Aug-05 11:39
memberaleks2343-Aug-05 11:39 
GeneralRe: textbox Pin
Kenny Young at 3-Aug-05 11:52
memberKenny Young3-Aug-05 11:52 
Questiondocument.all(&quot;DW&quot;) - ? Pin
Anonymous at 20-Jul-05 20:03
sussAnonymous20-Jul-05 20:03 
AnswerRe: document.all(&quot;DW&quot;) - ? Pin
Kenny Young at 21-Jul-05 3:26
memberKenny Young21-Jul-05 3:26 
GeneralListBox Pin
alandrizh at 12-Jul-05 7:13
memberalandrizh12-Jul-05 7:13 
GeneralMissing Zip File Pin
sserx at 8-Mar-05 0:16
membersserx8-Mar-05 0:16 
GeneralRe: Missing Zip File Pin
Kenny Young at 5-May-05 10:17
memberKenny Young5-May-05 10:17 
QuestionWhat is document.all(&quot;DW&quot;)? Pin
Joe Don Mitchell at 2-Mar-05 10:07
memberJoe Don Mitchell2-Mar-05 10:07 
AnswerRe: What is document.all(&quot;DW&quot;)? Pin
Kenny Young at 2-Mar-05 12:52
sussKenny Young2-Mar-05 12:52 
GeneralRe: What is document.all(&quot;DW&quot;)? Pin
Joe Don Mitchell at 3-Mar-05 5:10
memberJoe Don Mitchell3-Mar-05 5:10 
GeneralUsing Datagrid Pin
Ajit Ober at 17-Feb-05 9:13
sussAjit Ober17-Feb-05 9:13 
GeneralRe: Using Datagrid Pin
Kenny Young at 17-Feb-05 9:32
sussKenny Young17-Feb-05 9:32 
GeneralRe: Using Datagrid Pin
Ajit Ober at 17-Feb-05 10:38
sussAjit Ober17-Feb-05 10:38 
GeneralRe: Using Datagrid Pin
Kenny Young at 18-Feb-05 10:17
sussKenny Young18-Feb-05 10:17 
GeneralRe: Using Datagrid Pin
Anonymous at 28-Feb-05 5:07
sussAnonymous28-Feb-05 5:07 
GeneralRe: Using Datagrid Pin
Anonymous at 28-Feb-05 6:36
sussAnonymous28-Feb-05 6:36 
GeneralRe: Using Datagrid Pin
Ajit Ober at 28-Feb-05 9:44
sussAjit Ober28-Feb-05 9:44 
GeneralRe: Using Datagrid Pin
Ajit Ober at 28-Feb-05 9:46
sussAjit Ober28-Feb-05 9:46 

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

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

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