Reputation: 125
How to Sort ListBox in descending order on data-binding mode?
I give an example:
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";
Upvotes: 0
Views: 1263
Reputation: 125
I haven't got constructive answer and graceful solution yet. But with Rai and NicoRiff's help, I realize that we can't do more on Data-Binding mode, probably, I should do sorting before data-binding. Another thing I gained is that I should put Try and Catch to avoid silent crash and provide errors information in case accidentally call ListBox.Sorted =true or ListBox.Items.Add method on data-binding mode.
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."
Upvotes: 0
Reputation: 1635
use 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";
Upvotes: 1
Reputation: 4883
You can try this code:
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());
}
Upvotes: 0