2015-11-20 47 views
0

我有一些代碼在我的工作,使用ASP.net(我從來沒有碰過),但我需要排序它。下面是我需要Dscrp排序列表框:在ASP.net排序列表框

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(); 
} 

我發現這個鏈接:

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

所以我想在最後加入這樣的:

ddlProducts.Items.Sort(); 

但它只是給了我這個錯誤:

Does not contain a definition for 'Sort'

+0

你確定這是ASP經典? '.DataBind()'和你的C#標籤都讓我懷疑它。 – Martha

+0

@Martha不是100%確定,但它不是MVC。它使用aspx擴展名和aspx.cs作爲文件後面的代碼,所以我認爲這是遺留問題。 – djblois

+0

不,.aspx是asp.net的擴展。經典的asp只是使用.asp擴展名(並沒有「後面的代碼」的概念)。 – Martha

回答

1

如果您的應用程序在.NET 3.5或更高版本上,請查看MSDN: Extension Methods

您提供的tutorial link正在使用擴展方法概念,其中Sort()方法被裝飾到ListItemCollection(即ddlProducts.Items)類型上。

擴展方法應該在非泛型靜態類中定義。所以本教程缺少一個類定義。你可以嘗試:

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. 
} 

希望這對你有所幫助。

0

使用類似這樣的不完美,但它更新按照您的要求

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); 

    }