2017-01-03 114 views
0

如何在數據綁定模式下按降序對ListBox進行排序?如何在數據綁定模式下按降序對ListBox進行排序?

我舉一個例子:

System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument(); 
ArrayList paperSizes = new ArrayList(); 

for (int i = 0; i < printDoc.PrinterSettings.PaperSizes.Count; i++) 
{ 
    paperSizes.Add(printDoc.PrinterSettings.PaperSizes[i]); 
} 

listBox1.DataSource = paperSizes; 
listBox1.DisplayMember = "PaperName"; 
listBox1.ValueMember = "Kind"; 

回答

0

你可以試試這個代碼:

private void SortListBoxItems(ref ListBox lb) 
{ 
    List<object> items; 
    items = lb.Items.OfType<object>().ToList(); 
    lb.Items.Clear(); 
    lb.Items.AddRange(items.OrderByDescending(i => i).ToArray()); 
} 
+0

引發錯誤「設置數據源屬性時無法修改Items集合。」 – qtg

1

使用paperSizes.sort(paperSizes);

System.Drawing.Printing.PrintDocument printDoc = new System.Drawing.Printing.PrintDocument(); 
ArrayList paperSizes = new ArrayList(); 

for (int i = 0; i < printDoc.PrinterSettings.PaperSizes.Count; i++) 
{ 
    paperSizes.Add(printDoc.PrinterSettings.PaperSizes[i]); 
} 
paperSizes.sort(); 
listBox1.DataSource = paperSizes; 
listBox1.DisplayMember = "PaperName"; 
listBox1.ValueMember = "Kind"; 
+0

什麼是Collections.sort(paperSizes)?我需要按降序排序。我得到錯誤說{「無法比較數組中的兩個元素。」}當調用paperSizes.Sort();. – qtg

+0

您需要先獲取Kind of Papersize進行排序:printDoc.PrinterSettings.PaperSizes [i] .Kind.ToString() –

+0

如果我只是加載Kind,ArrayList可以排序,ListBox也可以排序。我知道它。但我的問題是如何在數據綁定模式下對ListBox進行排序。 – qtg

0

我還沒有建設性的答案和優雅的解決方案呢。但是在Rai和NicoRiff的幫助下,我意識到我們不能在數據綁定模式上做更多的事情,可能我應該在數據綁定之前進行排序。我獲得的另一件事是我應該把嘗試和捕捉,以避免無聲的崩潰,並提供錯誤信息,以防在數據綁定模式下意外調用ListBox.Sorted = true或ListBox.Items.Add方法。

1. In Rai's code sample, when we call paperSizes.sort(), VS catch error "Failed to compare two elements in the array." 
2. in Nico's code sample, because ListBox is on data-binding mode, VS will raise an error "Items collection cannot be modified when the DataSource property is set." 
相關問題