djblois
djblois

Reputation: 805

Sort ListBox in ASP.net

I have some code at my job that uses ASP.net (which I have never touched) but I need to sort it. Here is the ListBox that I need to sort by Dscrp:

    foreach (InteractiveInfo template in ddlsource)
    {
        Product thisProduct = FindProduct(template.UProductId);
        if (thisProduct != null)
        {
            ddlProducts.Items.Add(
                new ListItem(
                    string.Format("{0} ({1})", thisProduct.Dscrp, thisProduct.UProductId),
                    template.UProductId.ToString(CultureInfo.InvariantCulture)));
        }
    }
    ddlProducts.DataBind();
}

I found this link:

https://gist.github.com/chartek/1655779

so I tried adding this at the end:

ddlProducts.Items.Sort();

but it just gives me this error:

Does not contain a definition for 'Sort'

Upvotes: 0

Views: 1246

Answers (2)

Paramjit Raloowall
Paramjit Raloowall

Reputation: 1

Use something like this its not perfect but update it as per your requirement

    public static void Sort(this ListItemCollection items)
    {
        var itemsArray = new ListItem[items.Count];
        items.CopyTo(itemsArray,0);

        Array.Sort(itemsArray, (x, y) => (string.Compare(x.Value, y.Value, StringComparison.Ordinal)));
        items.Clear();
        items.AddRange(itemsArray);

    }

Upvotes: 0

Siva Gopal
Siva Gopal

Reputation: 3502

If your application is on .NET 3.5 or above, take a look at MSDN: Extension Methods.

The tutorial link you provided is making use of the extension method concept where Sort() method is decorated onto ListItemCollection (i.e. ddlProducts.Items) type.

The extension methods should be defined inside non-generic static class. So the tutorial missing a class definition. You can try with:

public static class ExtensionsMethods //Notice the static class
{
   public static void Sort(this ListItemCollection items)
   {
          //... Implement rest of logic from the tutorial
   }

   // Other extension methods, if required.
}

Hope this help you.

Upvotes: 1

Related Questions