Miguel Flores
Miguel Flores

Reputation: 147

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?

Upvotes: 0

Views: 194

Answers (2)

Tinwor
Tinwor

Reputation: 7973

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

Upvotes: 1

Utkarsh Bais
Utkarsh Bais

Reputation: 197

you can probably reverse (Using the Reverse method) your list "customersSaldo" before adding it, and then use the variable 'x' in increment order.

https://msdn.microsoft.com/en-us/library/b0axc2h2(v=vs.110).aspx

Upvotes: 0

Related Questions