C# ListBox - Sort Ascending and Descending

| Page Views: 2500 c# data sorting

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.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post