C# ListBox – Sort Ascending and Descending

0
User Management System
Learn Kotlin, Retrofit, MVVM and MySQL using this all-in-one app. It is designed to be beginner friendly.

So guys we see here how to sort ListBox data in C# windows forms.We sort both ascending and descending. This is what we do :

  • Fill up an array with data.
  • Fill our ListBox with that data.
  • When the user clicks the sort button we sort ascending.
  • When the user clicks again we sort descending and vice versa.

 

Here's the code :

using System;
using MetroFramework.Forms;

namespace CS_ListBox_Sort
{
    public partial class Form1 : MetroForm
    {
        //DECALARATIONS
        private readonly string[] spacecrafts = { "Kepler", "Casini", "Voyager", "New Horizon", "James Web", "Apollo 15", "Enterprise", "WMAP", "Spitzer", "Galileo" };
        private bool ascending = true;

        //constructor
        public Form1()
        {
            InitializeComponent();
            populate();
        }
        /*
         * POPULATE LISTBOX
         */
        private void populate()
        {
            listBox1.Items.Clear();
            foreach (var s in spacecrafts)
            {
                listBox1.Items.Add(s);
            }
        }

        /*
         * SORT
         */
        private void sort(bool asc)
        {
            //SORT ARRAY ASCENDING AND DESCENDING
            if (asc)
            {
                Array.Sort(spacecrafts);
            }
            else
            {
                Array.Reverse(spacecrafts);
            }

            //CLEAR AND POPULATE LISTBOX
            populate();

        }

        /*
         * SORT BUTTON CLICKED
         */
        private void sortBtn_Click(object sender, EventArgs e)
        {
            sort(ascending);
            ascending = !ascending;

        }

    }
}

Best Regards.

Android MySQL Retrofit2 Multipart CRUD,Search,Pagination rating

When I was a 2nd year Software Engineering student, I buillt a now defunct online tool called Camposha(from Campus Share) using my then favorite language C#(ASP.NET) to compete OLX in my country(Kenya). The idea was to target campus students in Kenya. I got a few hundred signups but competing OLX proved too daunting. I decided to focus on my studies, learning other languages like Java,Python,Kotlin etc while meanwhile publishing tutorials at my YouTube Channel ProgrammingWizards TV which led to this site(camposha.info). Say hello or post me a suggestion: oclemmi@gmail.com . Follow me below; Github , and on my channel: ProgrammingWizards TV

We will be happy to hear your thoughts

Leave a reply

+ sixty two = sixty four

Reset Password
Compare items
  • Total (0)
Compare
0
Shopping cart