.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Forum >> ASP.Net >> Post New QuestionBookmark and Share Subscribe to Forum

Sort items in combobox or dropdownlist in Asp.net

Posted By: Ramesh     Posted Date: January 27, 2009    Points:2   Category :ASP.Net
How to sort items alphabetically in a combobox or dropdownlist in asp.net.

Please help me to sort items i am using C# as my code.

Any help would be appreciated

Regards
Ramesh

Responses
Author: Akhil Raj       [Moderator]      
Posted Date: January 27, 2009     Points: 5   

hi friend,
When you return the query you use order by clause in query and sort it.

Author: Praveen             
Posted Date: January 28, 2009     Points: 5   

HI Ramesh,
yes Akhil is right you can Sort in the query level itself by order by clause.its good and best practice also, But if you want to sort in the client side here is the function


private void SortDropDown(DropDownList dd)
{
ListItem[] ar = null;
long i = 0;
foreach (ListItem li in dd.Items) {
Array.Resize(ref ar, i + 1);
ar(i) = li;
i += 1;
}
Array ar1 = ar;

ar1.Sort(ar1, new ListItemComparer());
dd.Items.Clear();
dd.Items.AddRange(ar1);
}

Compare class

private class ListItemComparer : IComparer
{

public int Compare(object x, object y)
{
ListItem a = x;
ListItem b = y;
CaseInsensitiveComparer c = new CaseInsensitiveComparer();
return c.Compare(a.Text, b.Text);
}
}


Happy Coding!!!
Praveen

Author: Athira Sreejith             
Posted Date: February 02, 2009     Points: 5   

Hi..

Try like this..


private void SortDDL(ref DropDownList objDDL)
{
ArrayList textList = new ArrayList();
ArrayList valueList = new ArrayList();

foreach (ListItem li in objDDL.Items)
{
textList.Add(li.Text);
}

textList.Sort();
foreach (object item in textList)
{
string value = objDDL.Items.FindByText(item.ToString()).Value;
valueList.Add(value);
}
objDDL.Items.Clear();

for (int i = 0; i < textList.Count; i++)
{
ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
objDDL.Items.Add(objItem);
}
}

Use:

SortDDL(ref this.ddlCusDivision);

Author: Kumar             
Posted Date: February 03, 2009     Points: 5   

Hi Ramesh,

Use SortedList object

Thanks and regards,
Kumar



Post Reply

You must Sign In To post reply
 
 
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery
JavaScript/VBScriptBiztalkWPFPatten/PracticesWCFOthers
www.DotNetSpark.comUnAnsweredAll

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend