C# Programming

Metro Framework - Fill ComboBox From An ArrayList

ComboBox is a common UI component used to show items in a dropdown list. Users can then choose from the dropdown list. Windows Forms provides combobox as a component. However, we can also use third party UI frameworks like MetroFramework. These frameworks give you the same capability and functionality as the default components. However, they are also visually very impressive and modern.

ComboBox ArrayList Metro

Pre-requisites

  1. The only pre-requisite is metroframework installed. You can install it via the nuget package manager.

Let's go

1. Add Using Statements

using System;
using System.Collections;
using MetroFramework.Forms;

These will add the System.Collections and MetroFrameworks.Froms to our namespace.

2.Create class inside of a namespace.

A namespace houses classes of related types. We place our class inside thenamespace.

namespace ComboBox_ArrayList
{
    public partial class Form1 : MetroForm
    {
    }
}

The class will import from MetroForm.

3. Method to Load data.

We'll create a method to load data for us. We'll instantiate a simple arraylist and bind to our ComboBox using the DataSource property of the combobox.

 private void loadData()
        {
            ArrayList spacecrafts = new ArrayList()
            {
                "Casini",
                "Enterpise",
                "Rosetter",
                "Saturn 5",
                "Apollo 15"
            };

            arraylist_ComboBox.DataSource = spacecrafts;
        }

4. Listen for SelectedIndexChanged.

You may want to listen for the changes of the selected index of our combobox. That is as the user selects an item from the combobox an event is raised which we then handle.

        private void arraylist_ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
}

5. Invoke the loadData method in constructor

 public Form1()
    {
        InitializeComponent();
        loadData();
    }

6. Putting All Together

using System;
using System.Collections;
using MetroFramework.Forms;

namespace ComboBox_ArrayList
{
    public partial class Form1 : MetroForm
    {
        public Form1()
        {
            InitializeComponent();
            loadData();
        }
        /*
         * LOAD ARRAYLIST TO COMBOBOX
         */
        private void loadData()
        {
            ArrayList spacecrafts = new ArrayList()
            {
                "Casini",
                "Enterpise",
                "Rosetter",
                "Saturn 5",
                "Apollo 15"
            };
            arraylist_ComboBox.DataSource = spacecrafts;
        }
        /*
         * COMBOBOX ITEM SELECTED LISTENER
         */
        private void arraylist_ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
    }
}