Wednesday, June 12, 2013

Generic Custom Paging and Sorting Using SQL Server and .Net C#


Compared to default paging, custom paging can improve the performance of paging through data by several orders of magnitude, through custom paging large amounts of data can reterive more efficiently than implementing default paging, however, especially when adding sorting to the mix. In this tutorial, we'll extend the example from the preceding one to include support for sorting and custom paging.

Implementation of Custom paging required following three parts.
  • Pager Control
  • Stored Procedure
  • Web page
Pager Control we need user control for add navigation buttons like move next, pervious, first and last button and later on to join with grid or any other control like repeater etc where we need paging functionality. You should perform following step to create user control. 1. Add user control from Open Visual Studio 2008 and choose File > New Item >User Control and rename the name with “Navigator.ascx” 2. Add four button for navigation move next, pervious, last and first record. 3. I use image button and add images through resource files
 

Code


<%@ Control Language="C#" AutoEventWireup="false" Codebehind="Navigator.ascx.cs" Inherits="DMS.Controls.Navigator" %><table border="0" width="100%"> <asp:HiddenField ID="hdnCurrentPage" runat="server" /> <asp:HiddenField ID="hdnTotalPages" runat="server" /> <asp:HiddenField ID="hdnSelectedValue" runat="server" /> <tr> <td> <table style="width: 100%"> <tr> <td align="center"> <asp:ImageButton ID="btnFirst" runat="server" CausesValidation="False" AlternateText="First" meta:resourcekey="btnFirstResource1" />&nbsp;&nbsp; <asp:ImageButton ID="btnPrevious" runat="server" CausesValidation="False" AlternateText="Previous" meta:resourcekey="btnPreviousResource2" />&nbsp;&nbsp;&nbsp;&nbsp; <asp:Label ID="Label3" runat="server" Text="Total Records: " meta:resourcekey="Label3Resource1" ></asp:Label> <asp:Label ID="lbltotalItem" runat="server" meta:resourcekey="lbltotalItemResource1" ></asp:Label> <asp:Label ID="Label4" runat="server" Text=", Page " meta:resourcekey="Label4Resource1" ></asp:Label> <asp:Label ID="lblcurrentpage" runat="server" Text="/" meta:resourcekey="lblcurrentpageResource1" ></asp:Label> <asp:Label ID="Label6" runat="server" Text=" of " meta:resourcekey="Label6Resource1" ></asp:Label> <asp:Label ID="lbltotalpages" runat="server" meta:resourcekey="lbltotalpagesResource1" ></asp:Label>&nbsp;&nbsp;&nbsp;&nbsp; <asp:ImageButton ID="btnNext" runat="server" CausesValidation="False" AlternateText="Next" meta:resourcekey="btnNextResource2" />&nbsp;&nbsp; <asp:ImageButton ID="btnLast" runat="server" CausesValidation="False" AlternateText="Last" meta:resourcekey="btnLastResource2" /> </td> </tr> </table> </td> </tr></table>

Code Behind


using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Globalization; namespace Controls { public partial class Navigator : System.Web.UI.UserControl { #region Fields private int _TotalRecord; private int _PageSize; #endregion #region Events // Delegates event for button click public event DataGridPageChangedEventHandler PageIndexChanged; #endregion #region Properties public int PageSize { get { return _PageSize; } set { _PageSize = value; } } public int TotalRecord { get { return _TotalRecord; } set { _TotalRecord = value; lbltotalItem.Text = Convert.ToString(_TotalRecord); } } #endregion #region Data public void Initialize(int totalRecords, int pageSize) { try { TotalRecord = totalRecords; _PageSize = pageSize; if ((_TotalRecord % _PageSize) == 0) TotalPages = _TotalRecord / _PageSize; else TotalPages = (_TotalRecord / _PageSize) + 1; CurrentPage = 1; EnableLinks(); } catch (Exception ex) { throw; } } private void EnableLinks() { try { if (CurrentPage == 1) { btnFirst.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "FirstImageD").ToString(); btnFirst.Enabled = false; btnPrevious.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "PreviousImageD").ToString(); btnPrevious.Enabled = false; } else { btnFirst.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "FirstImageE").ToString(); btnFirst.Enabled = true; btnPrevious.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "PreviousImageE").ToString(); btnPrevious.Enabled = true; } if (CurrentPage == TotalPages) { btnNext.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "NextImageD").ToString(); btnNext.Enabled = false; btnLast.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "LastImageD").ToString(); btnLast.Enabled = false; } else { btnNext.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "NextImageE").ToString(); btnNext.Enabled = true; btnLast.ImageUrl = HttpContext.GetGlobalResourceObject("Resource", "LastImageE").ToString(); btnLast.Enabled = true; } } catch (Exception ex) { throw; } } #endregion protected void OnPageIndexChanged(object sender) { try { if (PageIndexChanged != null) PageIndexChanged(this, new DataGridPageChangedEventArgs(sender, CurrentPage)); EnableLinks(); } catch (Exception ex) { throw; } } #region Event Handlers void btnFirst_Click(object sender, ImageClickEventArgs e) { try { if (CurrentPage > 1) CurrentPage = 1; OnPageIndexChanged(sender); //EnableLinks(); } catch (Exception ex) { throw; } } void btnPrevious_Click(object sender, ImageClickEventArgs e) { try { if (CurrentPage > 1) CurrentPage--; OnPageIndexChanged(sender); //EnableLinks(); } catch (Exception ex) { throw; } } void btnNext_Click(object sender, ImageClickEventArgs e) { try { if (CurrentPage < TotalPages) CurrentPage++; OnPageIndexChanged(sender); } catch (Exception ex) { throw; } } void btnLast_Click(object sender, ImageClickEventArgs e) { try { if (CurrentPage < TotalPages) CurrentPage = TotalPages; OnPageIndexChanged(sender); } catch (Exception ex) { throw; } } #endregion #region Web Form Designer generated code override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); //CreateControls(); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { //this.Load += new System.EventHandler(this.Page_Load); this.btnFirst.Click += new ImageClickEventHandler(btnFirst_Click); this.btnPrevious.Click += new ImageClickEventHandler(btnPrevious_Click); this.btnNext.Click += new ImageClickEventHandler(btnNext_Click); this.btnLast.Click += new ImageClickEventHandler(btnLast_Click); } #endregion #region Hidden Fields public int CurrentPage { get { return int.Parse((!string.IsNullOrEmpty(hdnCurrentPage.Value) ? hdnCurrentPage.Value : "1")); } set { hdnCurrentPage.Value = Convert.ToString(value); lblcurrentpage.Text = Convert.ToString(hdnCurrentPage.Value,CultureInfo.CurrentCulture); } } public int TotalPages { get { return int.Parse(hdnTotalPages.Value); } set { hdnTotalPages.Value = Convert.ToString(value); lbltotalpages.Text = hdnTotalPages.Value; } } public string SelectedValue { get { return this.hdnSelectedValue.Value; } set { this.hdnSelectedValue.Value = value; } } #endregion } }

 Stored Procedure

Create the Table name customer add some major fields like customer name ,Customer ID , Phone No etc  and insert dummy data then we will create the stored procedure for custom paging and sorting

/****** Object: StoredProcedure [dbo].[usp_CustomerSearch] Script Date: 11/24/2011 12:34:19 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[usp_CustomerSearch] @Customer_ID int =Null, @Customer_Name varchar(MAX)=Null, @Phone_No varchar(MAX)=Null, @Address varchar(MAX)=Null, @SortDir VARCHAR(30) = 'ASC', @SortOrder VARCHAR(max) ='Customer_Name' , @PageNumber INT = 1, @PageSize INT = 25ASBEGIN SET NOCOUNT ON; DECLARE @FirstRow INT DECLARE @LastRow INT SET XACT_ABORT ON; DECLARE @SQL NVARCHAR(4000) SELECT @FirstRow = (@PageNumber - 1) * @PageSize + 1, @LastRow = @PageSize + (@PageNumber - 1) * @PageSize; IF @SortORder IS NULL OR @SortOrder = '' SET @SortOrder = 'DESC'; WITH TempCustomer AS ( SELECT * , ROW_NUMBER() OVER (ORDER BY CASE @SortDir WHEN 'DESC' THEN NULL ELSE CASE @SortOrder WHEN 'Customer_ID' THEN CONVERT(VARCHAR(50),Customer_ID) WHEN 'Customer_Name' THEN Customer_Name WHEN 'Phone_No' THEN Phone_No WHEN 'Address' THEN Address ELSE Customer_Name END END ASC) AS RowNumberAsc, ROW_NUMBER() OVER (ORDER BY CASE @SortDir WHEN 'ASC' THEN NULL ELSE CASE @SortOrder WHEN 'Customer_ID' THEN CONVERT(VARCHAR(50),Customer_ID) WHEN 'Customer_Name' THEN Customer_Name WHEN 'Phone_No' THEN Phone_No WHEN 'Address' THEN Address ELSE Customer_Name END END DESC) AS RowNumberDesc FROM ( SELECT [Customer_ID], [Customer_Name], [Phone_No], [Address] FROM [dbo].[Customer] (NOLOCK) WHERE 1 = 1 AND (LOWER(Customer_Name) LIKE '%'+ @Customer_Name +'%' or @Customer_Name is null) AND (LOWER(Phone_No) LIKE '%'+ @Phone_No +'%' or @Phone_No is null) AND (LOWER(Address) LIKE '%'+ @Address +'%' or @Address is null) AND (LOWER(Customer_ID)= @Customer_ID or @Customer_ID is null) ) AS TempRow ) SELECT *,(SELECT COUNT(*) FROM TempCustomer) AS TotalRecords FROM TempCustomer WHERE CASE @SortDir WHEN 'DESC' THEN RowNumberDesc ELSE RowNumberAsc END BETWEEN @FirstRow AND @LastRow Order By CASE @SortDir WHEN 'DESC'THEN RowNumberDesc ELSE RowNumberAsc END; ENDGO
In Above stored procedure some fields extra taking as input like SortDir,SortOrder,PageNumber and PageSize.

Fields Details

SortDir : Use for order by direction means “ASC” or “DESC”
SortOrder: Field name on which you want to sort like “Customer_Name” or “Phone_No” etc
PageNumber: Current page number e.g ( when user click next then current page number 2 and so on)
PageSize : Grid page size how many records wants to show in a grid

Aspx Page Code to populate and binding of grid.

Add Grid in a aspx page also add navigator control for created before for paging as shown example given below

HTML Page

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" EnableEventValidation="true" %><%@ Register Src="Navigator.ascx" TagName="Navigator" TagPrefix="uc1" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> </div> <asp:GridView ID="GridView1" runat="server" AllowSorting="true"> <Columns> <asp:BoundField DataField="Customer_ID" HeaderText="Customer ID" SortExpression="Customer_ID"> <HeaderStyle Width="10%" /> </asp:BoundField> <asp:BoundField DataField="Customer_Name" HeaderText="Contact Person" SortExpression="Customer_Name"> <HeaderStyle Width="20%" /> </asp:BoundField> <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address"> <HeaderStyle Width="20%" /> </asp:BoundField> <asp:BoundField DataField="Phone_No" HeaderText="Phone No" SortExpression="Phone_No" > <HeaderStyle Width="10%" /> </asp:BoundField> </Columns> </asp:GridView> <uc1:Navigator ID="Navigator1" runat="server" /> </form></body></html>

Code Behind

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Globalization; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected override void OnInit(EventArgs e) { base.OnInit(e); Initializer(); } private void Initializer() { Page.Load += new EventHandler(Page_Load); GridView1.Sorting += new GridViewSortEventHandler(GridView1_Sorting); Navigator1.PageIndexChanged += new DataGridPageChangedEventHandler(Navigator1_PageIndexChanged); } void Navigator1_PageIndexChanged(object source, DataGridPageChangedEventArgs e) { DoSearchAndSetData(Convert.ToString(ViewState["sortOrder"]), e.NewPageIndex); } void GridView1_Sorting(object sender, GridViewSortEventArgs e) { if (ViewState["sortdir"] == null) { ViewState["sortdir"] = "desc"; } else if (Convert.ToString(ViewState["sortdir"]).ToLower() == "desc") { ViewState["sortdir"] = "asc"; } else { ViewState["sortdir"] = "desc"; } string[] sort = e.SortExpression.Split('.'); ViewState["sortOrder"] = e.SortExpression; DoSearchAndSetData(e.SortExpression, 1); } void DoSearchAndSetData(string sortExperssion, int pageNumber) { int _pageSize = 25; try { ModelCustomer objModel = new ModelCustomer(); objModel.SortOrder = sortExperssion; objModel.SortDir = Convert.ToString(ViewState["sortdir"]); objModel.PageNo = pageNumber; objModel.PageSize = _pageSize; List<ModelCustomer> colModel = new List<ModelCustomer>(); colModel = DalCustomer.Search(objModel); if (colModel.Count > 0 && colModel != null) { Navigator1.Visible = true; if (pageNumber == 1) this.Navigator1.Initialize(Convert.ToInt32(colModel[0].TotalRecords, CultureInfo.CurrentCulture), _pageSize); } else { Navigator1.Visible = false; } GridView1.DataSource = colModel; GridView1.DataBind(); } catch (Exception ex) { throw; } } } }

Sunday, October 9, 2011

Moving,Sorting and Searching Items between two Generic Listbox controls

 

I will explain you how to create user control using two listbox control and moving,filtering and searching items between them.First of all you should add two listbox and add the buttons like given below.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ucListBox.ascx.cs" Inherits="ucListBox" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<script type="text/javascript" language="javascript">
var ddlText, ddlValue, ddl, lblMesg;
function CacheItems() {

ddlText = new Array();
ddlValue = new Array();
ddl = document.getElementById("<%=lstAvailable.ClientID %>");

for (var i = 0; i < ddl.options.length; i++) {
ddlText[ddlText.length] = ddl.options[i].text;
ddlValue[ddlValue.length] = ddl.options[i].value;
}
}

window.onload = CacheItems;

function FilterItems(value) {

ddl.options.length = 0;
for (var i = 0; i < ddlText.length; i++) {
if (ddlText[i].toLowerCase().indexOf(value) != -1) {
AddItem(ddlText[i], ddlValue[i]);
}
}

if (ddl.options.length == 0) {
AddItem("", "");
}
}

function AddItem(text, value) {

var opt = document.createElement("option");
opt.text = text;
opt.value = value;
ddl = document.getElementById("<%=lstAvailable.ClientID %>");
ddl.options.add(opt);
}

</script>

<table width="100%" border="0">
<tr>
<td style="width: 19%; height: 24px;" runat="server" id="tdd">
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" Text="Search" ID="lblSearch" meta:resourcekey="lblSearchResource1"></asp:Label>
</strong></span>
</td>
<td>
<asp:TextBox ID="txtSearch" runat="server" onkeyup="FilterItems(this.value)" meta:resourcekey="txtSearchResource1"></asp:TextBox><br />
</td>
</tr>
</table>
<table width="60%">
<tr>
<td>
</td>
</tr>
<tr align="center">
<td align="center">
<!-- Start list box-->
<table width="100%">
<tr>
<td valign="top">
<table border="0" width="100%">
<tr>
<td>
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" ID="lblAvailable" Text="Available" meta:resourcekey="lblAvailableResource2"></asp:Label>
</strong></span>
</td>
</tr>
<tr>
<td style="height: 200px">
<asp:ListBox ID="lstAvailable" runat="server" Font-Size="8pt" Height="100%" SelectionMode="Multiple"
Width="300px" meta:resourcekey="lstAvailableResource1"></asp:ListBox>
</td>
</tr>
</table>
</td>
<td align="center" valign="top">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnAddAll" runat="server" ImageUrl="~/Images/Last.png" CausesValidation="False" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Next.png" CausesValidation="False" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnRemove" runat="server" CausesValidation="False" ImageUrl="~/Images/Previous.png" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnRemoveAll" runat="server" CausesValidation="False" ImageUrl="~/Images/First.png" />
</td>
</tr>
</table>
</td>
<td valign="top">
<table width="100%">
<tr>
<td>
<span style="font-size: 8pt"><strong>
<asp:Label runat="server" ID="lblAdded" Text="Added" meta:resourcekey="lblAddedResource2"></asp:Label>
</strong></span>
</td>
</tr>
<tr>
<td style="height: 200px">
<asp:ListBox ID="lstAdded" runat="server" Font-Size="8pt" Height="100%" SelectionMode="Multiple"
Width="300px" meta:resourcekey="lstAddedResource1"></asp:ListBox>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:ImageButton ID="btnMoveUp" runat="server" CausesValidation="False" ImageUrl="~/Images/MoveUp.png" />
</td>
</tr>
<tr>
<td>
<asp:ImageButton ID="btnMoveDown" runat="server" CausesValidation="False" ImageUrl="~/Images/Movedown.png" />
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- end list box-->
</td>
</tr>
</table>



Now let’s, create a method for Moving the items between two ListBox. Here’s the code block below:



using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class ucListBox : System.Web.UI.UserControl
{

#region Property
private IList _DataSourceAvailable = null;
private IList _DataSourceAdded = null;
private string _dataTextFieldAvailable = string.Empty;
private string _dataValueFieldAvailable = string.Empty;
private string _dataTextFieldAdded = string.Empty;
private string _dataValueFieldAdded = string.Empty;
private string _availableItemText = "Available Items";
private string _addedItemText = "Added Items";
protected ArrayList arlList = new ArrayList();

/// <summary>
/// Gets or sets the available item text.
/// </summary>
/// <value>The available item text.</value>
///

public string AvailableItemText {
get { return _availableItemText; }
set { _availableItemText = value; }
}

/// <summary>
/// Gets or sets the added items text.
/// </summary>
/// <value>The added items text.</value>
public string AddedItemsText
{
get { return _addedItemText; }
set { _addedItemText = value; }
}

/// <summary>
/// Gets the available items.
/// </summary>
/// <value>The available items.</value>
public ListItemCollection AvailableItems
{
get { return lstAvailable.Items; }
}

/// <summary>
/// Gets the added items.
/// </summary>
/// <value>The added items.</value>
public ListItemCollection AddedItems
{
get { return lstAdded.Items; }
}

/// <summary>
/// Gets or sets the data source for the available items listbox.
/// </summary>
/// <value>The data source for available items.</value>
public IList DataSourceAvailable
{
get { return _DataSourceAvailable; }
set { _DataSourceAvailable = value; }
}

/// <summary>
/// Gets or sets the data source for the added items listbox.
/// </summary>
/// <value>The data source for added items.</value>
public IList DataSourceAdded
{
get { return _DataSourceAdded; }
set { _DataSourceAdded = value; }
}

/// <summary>
/// Gets or sets the data text field available.
/// </summary>
/// <value>The data text field available.</value>
public string DataTextFieldAvailable
{
get { return _dataTextFieldAvailable; }
set { _dataTextFieldAvailable = value; }
}

/// <summary>
/// Gets or sets the data value field available.
/// </summary>
/// <value>The data value field available.</value>
public string DataValueFieldAvailable
{
get { return _dataValueFieldAvailable; }
set { _dataValueFieldAvailable = value; }
}

/// <summary>
/// Gets or sets the data text field added.
/// </summary>
/// <value>The data text field added.</value>
public string DataTextFieldAdded
{
get { return _dataTextFieldAdded; }
set { _dataTextFieldAdded = value; }
}

/// <summary>
/// Gets or sets the data value field added.
/// </summary>
/// <value>The data value field added.</value>
public string DataValueFieldAdded
{
get { return _dataValueFieldAdded; }
set { _dataValueFieldAdded = value; }
}
#endregion

#region Method
protected void Page_Load(object sender, EventArgs e)
{


}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Initializer();

}
public void Initializer()
{
btnAdd.Click += new ImageClickEventHandler(btnAdd_Click);
btnAddAll.Click += new ImageClickEventHandler(btnAddAll_Click);
btnRemove.Click += new ImageClickEventHandler(btnRemove_Click);
btnRemoveAll.Click += new ImageClickEventHandler(btnRemoveAll_Click);
btnMoveUp.Click += new ImageClickEventHandler(btnMoveUp_Click);
btnMoveDown.Click += new ImageClickEventHandler(btnMoveDown_Click);
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;
}



public void BindAvailableList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Added List Control
lstAvailable.DataSource = this.DataSourceAvailable;
lstAvailable.DataTextField = this.DataTextFieldAvailable;
lstAvailable.DataValueField = this.DataValueFieldAvailable;
lstAvailable.DataBind();
}
public void BindAddedList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Available List Control
lstAdded.DataSource = this.DataSourceAdded;
lstAdded.DataTextField = this.DataTextFieldAdded;
lstAdded.DataValueField = this.DataValueFieldAdded;
lstAdded.DataBind();
}

public void BindList()
{
//Set the Header Text of the Available and Added Items
lblAdded.Text = this.AddedItemsText;
lblAvailable.Text = this.AvailableItemText;

//Bind the Available and Added List Controls
lstAdded.DataSource = this.DataSourceAdded;
lstAdded.DataTextField = this.DataTextFieldAdded;
lstAdded.DataValueField = this.DataValueFieldAdded;
lstAdded.DataBind();

lstAvailable.DataSource = this.DataSourceAvailable;
lstAvailable.DataTextField = this.DataTextFieldAvailable;
lstAvailable.DataValueField = this.DataValueFieldAvailable;
lstAvailable.DataBind();


#region Remove intersection Record
ArrayList ary = new ArrayList();

for (int i = 0; i < lstAvailable.Items.Count; i++)
{
for (int j = 0; j < lstAdded.Items.Count; j++)
{

if (lstAvailable.Items[i].Value == lstAdded.Items[j].Value)
{
// lstAvailable.RemoveAt(i);
if (!ary.Contains(lstAvailable.Items[i]))
{
ary.Add(lstAvailable.Items[i]);
j = -1;
}
break;
}

}

}
for (int i = 0; i < ary.Count; i++)
{
lstAvailable.Items.Remove(((ListItem)ary[i]));

}

#endregion

ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", "CacheItems();", true);
//ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", "UploadFileToParent();", true);
}

#endregion

#region Navigation

/// <summary>
/// Add all the selected items from the Available Items to the Added Items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnAdd_Click(object sender, EventArgs e)
{
if (lstAvailable.SelectedIndex >= 0)
{
for (int i = 0; i < lstAvailable.Items.Count; i++)
{
if (lstAvailable.Items[i].Selected)
{
if (!arlList.Contains(lstAvailable.Items[i]))
arlList.Add(lstAvailable.Items[i]);
}
}
for (int i = 0; i < arlList.Count; i++)
{
if (!lstAdded.Items.Contains((ListItem)arlList[i]))
lstAdded.Items.Add((ListItem)arlList[i]);
lstAvailable.Items.Remove((ListItem)arlList[i]);
}
}
}

/// <summary>
/// Add all the items from the Available items to the Added Items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnAddAll_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstAvailable.Items)
{
lstAdded.Items.Add(list);
}
lstAvailable.Items.Clear();
}

/// <summary>
/// Moves the Selected items from the Added items to the Available items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnRemove_Click(object sender, EventArgs e)
{
if (lstAdded.SelectedIndex >= 0)
{
for (int i = 0; i < lstAdded.Items.Count; i++)
{
if (lstAdded.Items[i].Selected)
{
if (!arlList.Contains(lstAdded.Items[i]))
arlList.Add(lstAdded.Items[i]);
}
}
for (int i = 0; i < arlList.Count; i++)
{
if (!lstAvailable.Items.Contains((ListItem)arlList[i]))
lstAvailable.Items.Add((ListItem)arlList[i]);
lstAdded.Items.Remove((ListItem)arlList[i]);
}
}
}

/// <summary>
/// Moves all the items from the Added items to the Available items
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnRemoveAll_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstAdded.Items)
{
lstAvailable.Items.Add(list);
}
lstAdded.Items.Clear();
}

/// <summary>
/// Move item to upwards
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnMoveDown_Click(object sender, ImageClickEventArgs e)
{
try
{
int startindex = lstAdded.Items.Count - 1;
for (int i = startindex; i > -1; i--)
{
if (lstAdded.Items[i].Selected)//identify the selected item
{
//swap with the lower item(move down)
if (i < startindex && !lstAdded.Items[i + 1].Selected)
{
ListItem bottom = lstAdded.Items[i];
lstAdded.Items.Remove(bottom);
lstAdded.Items.Insert(i + 1, bottom);
lstAdded.Items[i + 1].Selected = true;
}

}
}
}
catch (Exception ex)
{

}
}

/// <summary>
/// Move Item To down Words
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void btnMoveUp_Click(object sender, ImageClickEventArgs e)
{
try
{
for (int i = 0; i < lstAdded.Items.Count; i++)
{
if (lstAdded.Items[i].Selected)//identify the selected item
{
//swap with the top item(move up)
if (i > 0 && !lstAdded.Items[i - 1].Selected)
{
ListItem bottom = lstAdded.Items[i];
lstAdded.Items.Remove(bottom);
lstAdded.Items.Insert(i - 1, bottom);
lstAdded.Items[i - 1].Selected = true;
}
}
}

}
catch (Exception ex)
{

}
}

#endregion
}