Click here to Skip to main content
6,292,426 members and growing! (10,375 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate

ASP.NET - Drag and Drop on a Webpage

By Kenny Young

Drag and drop contained objects on a webpage.
C#, Windows, .NET 1.0, ASP.NET, Dev
Posted:28 Dec 2004
Views:144,003
Bookmarked:95 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
26 votes for this article.
Popularity: 5.77 Rating: 4.08 out of 5
3 votes, 11.5%
1
1 vote, 3.8%
2
1 vote, 3.8%
3
8 votes, 30.8%
4
13 votes, 50.0%
5

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


Member
B.S. - University of South Florida.

Ken currently works as a software architect at the Pediatrics Epidemiology Center at the University of South Florida. He is involved in the architecture and design on numerous clinical trial projects at the center. Some of the project include:

1. Rare Diseases Clinical Research Network
2. Florida Neurofibromatosis
3. Cystic Fibrosis
4. AIDA
5. TrialNet
Occupation: Architect
Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberMember 449609921:55 22 Jun '09  
GeneralGood Article Pinmemberkhanjee7718:30 30 Dec '08  
GeneralMy vote of 2 PinmemberIyigun Cevik3:47 8 Dec '08  
Generalhii kenny Young Pinmemberctcalyx22:06 6 Aug '07  
GeneralRe: hii kenny Young PinmemberRockrebel2:42 7 Aug '08  
GeneralRe: hii kenny Young PinmemberKenny Young3:26 7 Aug '08  
QuestionHyperLinkBitmap Error Pinmemberdiddy4337:39 2 Jul '07  
GeneralDoens't work with firefox Pinmembercarlintveld8:50 31 May '07  
GeneralRe: Doens't work with firefox Pinmembervytas z.3:33 16 Aug '07  
GeneralRe: Doens't work with firefox Pinmemberbbol13:49 19 Nov '07  
GeneralDoes n't Work with ASP.Net 2005 PinmemberHari Darshan2:17 26 Apr '07  
GeneralHow to get updated row after drag? Pinmemberdavihigh4:29 12 Sep '06  
GeneralRe: How to get updated row after drag? PinmemberKenny Young8:15 12 Sep '06  
QuestionCheckbox. Pinmemberpy1rdj12:20 4 Sep '06  
AnswerRe: Checkbox. PinmemberKenny Young8:17 12 Sep '06  
QuestionDrag n Drop from listbox to a datagrid Pinmemberkumarcs5:11 4 Sep '06  
AnswerRe: Drag n Drop from listbox to a datagrid PinmemberKenny Young8:21 12 Sep '06  
GeneralDatagrid to Datagrid drag drop Pinmembersandeepautade3:31 31 Aug '06  
GeneralRe: Datagrid to Datagrid drag drop PinmemberKenny Young3:39 31 Aug '06  
GeneralDRAG DROP PinmemberMon221:45 17 Aug '06  
GeneralRe: DRAG DROP PinmemberKenny Young3:37 31 Aug '06  
Generalmicrosoft treeview [modified] Pinmemberazidi15:37 13 Jul '06  
GeneralThe DIV does not move PinmemberSebastian_M2:07 7 Mar '06  
GeneralRe: The DIV does not move PinmemberSebastian_M4:07 7 Mar '06  
GeneralRe: The DIV does not move PinmemberSaurabhdotnet2:08 23 Mar '06  

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

PermaLink | Privacy | Terms of Use
Last Updated: 28 Dec 2004
Editor: Rinish Biju
Copyright 2004 by Kenny Young
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project