Miguel Flores Miguel Flores - 1 month ago 11
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) {
listCustomers.Items.Clear();
List < Customer > customers = CustomerList.GetCustomers();
List < CustomerSaldo > customersSaldo = CustomerListSaldo.GetCustomers();
int total = 0;
int totalCustomer = 0;
foreach(Customer customer in customers)
total++;

listCustomers.Items.Clear();

totalCustomer = total;
int x = totalCustomer;

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

}
}

}


Result

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
x
, 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

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

//Reverse the list
customersSaldo.Reverse();
//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);
Comments