如何在数据绑定模式下按降序对列表框进行排序



如何在数据绑定模式下按降序对列表框进行排序?

我举个例子:

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

使用 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";

您可以尝试以下代码:

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

我还没有建设性的答案和优雅的解决方案。但是在 Rai 和 NicoRiff 的帮助下,我意识到我们不能在数据绑定模式下做更多的事情,也许,我应该在数据绑定之前进行排序。我获得的另一件事是,我应该将 Try and catch 放在避免静默崩溃并提供错误信息,以防意外调用 ListBox.Sort =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."

最新更新