Sakthivel
Sakthivel

Reputation: 1941

How can I insert an item to a listbox in its alphabetical place?

I develop a webpage in that I display a list box items which is fetched from a database. Dynamically I added some items into it. It adds to the end of the list box, so I want to sort the list box item after I add items. I tried Arraylist for sorting, but it is not working.

Upvotes: 11

Views: 22306

Answers (7)

Carl Heinrich Hancke
Carl Heinrich Hancke

Reputation: 2810

I was looking at a way of doing this without comparer classes, ArrayLists etc. So I thought I'd paste the method I had used for others:

Please note that my method uses LINQ to Objects, so it will only work in newer versions of the Framework.

// get a LINQ-enabled list of the list items
List<ListItem> list = new List<ListItem>(ListBoxToSort.Items.Cast<ListItem>());
// use LINQ to Objects to order the items as required
list = list.OrderBy(li => li.Text).ToList<ListItem>();
// remove the unordered items from the listbox, so we don't get duplicates
ListBoxToSort.Items.Clear();
// now add back our sorted items
ListBoxToSort.Items.AddRange(list.ToArray<ListItem>());

Upvotes: 24

Ed M
Ed M

Reputation: 94

Here is the vb code

Private Sub SortList(ByVal lb As DropDownList)
    ' get a LINQ-enabled list of the list items
    Dim list As New List(Of ListItem)(lb.Items.Cast(Of ListItem)())
    ' use LINQ to Objects to order the items as required
    list = list.OrderBy(Function(li) li.Text).ToList()
    ' remove the unordered items from the listbox, so we don't get duplicates
    lb.Items.Clear()
    ' now add back our sorted items
    lb.Items.AddRange(list.ToArray())
End Sub

Upvotes: -1

Zinx
Zinx

Reputation: 2349

You have to sort the datatable before assigning as a datasource to the list box.

DataTable.DefaultView.sort = "[Column Name]".

As you mentioned that you are using Add method to add the ListItems into List, Add method always appends the ListItems. You can add Items at desired index by using Insert method with index. List.Insert(ListItem, index)

Upvotes: 0

Nancy Rocio
Nancy Rocio

Reputation: 1

I know this is very similar to the response of The King, but this is how it worked for me.

System.Collections.SortedList sorted = new System.Collections.SortedList();

foreach (ListItem ll in ListInQuestion.Items)
{
    sorted.Add(ll.Value, ll.Text);//yes, first value, then text
}

ListInQuestion.Items.Clear();

foreach (String key in sorted.Keys)
{
    ListInQuestion.Items.Add(new ListItem(sorted[key].ToString(), key));// <-- look here!
}

I hope this works for someone else.

Upvotes: -1

The King
The King

Reputation: 4650

Try this code in PreRender event of your ListBox.

System.Collections.SortedList sorted = new SortedList();

foreach (ListItem ll in ListBox1.Items)
{
    sorted.Add(ll.Text, ll.Value);
}

ListBox1.Items.Clear();

foreach (String key in sorted.Keys)
{
    ListBox1.Items.Add(new ListItem(key, sorted[key].ToString()));
}

Upvotes: 4

Himadri
Himadri

Reputation: 8876

Try the following code:

 DataTable dt = new DataTable();
            dt.Columns.Add("val", Type.GetType("System.Int32"));
            DataRow dr;
            for (int i = 1; i <= 31; i++)
            {
                dr = dt.NewRow();
                dr[0] = i;
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            DataView dv = dt.DefaultView;
            dv.Sort = "val desc";
            ddlDay.DataTextField = "val";
            ddlDay.DataValueField = "val";
            ddlDay.DataSource = dv.ToTable();
            ddlDay.DataBind();

If u r binding the listbox by setting datasource as DataTable populated with db data then when you want to add a new item instead of adding the item add the record to the datatable. Then create a dataview for that datatable, sort the data in the dataview as below:

DataView dv = dt.DefaultView;
                dv.Sort = "val desc";

then set the datasource of listbox as dv.ToTable()

Upvotes: 1

eugeneK
eugeneK

Reputation: 11126

Do you mean by dynamically that you add items to list via Javascript or after post back of somekind using ASP.NET controls ?

If you add dynamically using Javascript then your answer would be sorting with jQuery and if after postback using ASP.NET then you should use List object located at System.Collections.Generic.

Upvotes: -1

Related Questions