Miguel Flores Miguel Flores - 1 year ago 97
C# Question

Sort C# ListBox Items

I'm using C# Adapter method, I add elements to a list and after that I call that list to fill a listbox, here is my button for do that:

private void button1_Click(object sender, EventArgs e) {
List < Customer > customers = CustomerList.GetCustomers();
List < CustomerSaldo > customersSaldo = CustomerListSaldo.GetCustomers();
int total = 0;
int totalCustomer = 0;
foreach(Customer customer in customers)


totalCustomer = total;
int x = totalCustomer;

foreach(CustomerSaldo customer2 in customersSaldo) {
if (x >= 1) {
listCustomers.Items.Add("Costumer ID # " + x + " is: " + customer2.Saldo);




This is what I get, it's ok but I want to know if exists a way to do this like this example:

Costumer #1 Saldo...

Costumer #2 Saldo...

Costumer #3 Saldo...

If you see my code I have a variable
, this variable is the total number of costumers, so I think that my sort has to start with this variable, but I don't know exactly how to do it, what can I do?

Answer Source

Reverse the list and start counting untill you reach the end:

//Reverse the list
//Add new items
for(int i = 0; i < customers.Count; i++) 
    listCustomers.Items.Add(string.Format("Costumer ID # {0} is: {1}", (i+1).ToString(), customersSaldo[i].Saldo);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download