Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Rearranging ASP.NET ListView Items using JavaScript

5.00/5 (4 votes)
17 Dec 2012CPOL 20.1K   211  
This article discusses a simple way of rearranging the ASP.NET ListView Items using JavaScript.

Introduction

This tip discusses a simple way of rearranging the ASP.NET ListView Items using JavaScript.

Background

There are some scenarios when we want to rearrange the ListView items on an ASP.NET web page. This small tip explains a simple method to do the same.

Using the Code 

The basic idea behind the sample code is to find out the user selected index for the listview. We will then see where the user wants to move this item to. Then we will simply take the selected index as old index and the desired index as new index and swap the value and text for these two items on client side using JavaScript.

JavaScript
function MoveItemUpDown(goUp) 
{
	var list = document.getElementById('lstACitem');   
	//Get the current selected items index
	var selectedIndex = list.selectedIndex;
	
	//tell the user to select one if he hasn't
	if (selectedIndex == -1)
	{ 
		alert("Select an item for re-ordering.");
	}    
	else 
	{
		//check if we need to move up or down
		var newIndex = selectedIndex+ (goUp ? -1 : 1);
					
		if (newIndex < 0) 
		{
			//If we have reached top cycle it to end
			newIndex = list.length-1;
		}
		else if(newIndex >= list.length)
		{
			//If we have reached end cycle it to top
			newIndex = 0;
		}   
		 
		//Lets take the old items value and text
		var oldVal = list[selectedIndex].value;
		var oldText = list[selectedIndex].text;
		
		//Swap the value and text of old and new items.  
		list[selectedIndex].value = list[newIndex].value;
		list[selectedIndex].text = list[newIndex].text;
		list[newIndex].value = oldVal;
		list[newIndex].text = oldText;
		list.selectedIndex = newIndex;
		
		//Done, the element is moved now
	}
}     

When we run the code, we can see the list items getting rearranged and all this is being done on the client side.

Image 1

Point of Interest

This small tip has been written so that developers asking the similar question on "Quick Answers" can find a solution for such problems easily.

History

  • 14th August 2012: First post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)