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
.
function MoveItemUpDown(goUp)
{
var list = document.getElementById('lstACitem');
var selectedIndex = list.selectedIndex;
if (selectedIndex == -1)
{
alert("Select an item for re-ordering.");
}
else
{
var newIndex = selectedIndex+ (goUp ? -1 : 1);
if (newIndex < 0)
{
newIndex = list.length-1;
}
else if(newIndex >= list.length)
{
newIndex = 0;
}
var oldVal = list[selectedIndex].value;
var oldText = list[selectedIndex].text;
list[selectedIndex].value = list[newIndex].value;
list[selectedIndex].text = list[newIndex].text;
list[newIndex].value = oldVal;
list[newIndex].text = oldText;
list.selectedIndex = newIndex;
}
}
When we run the code, we can see the list items getting rearranged and all this is being done on the client side.
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