C# Windows Forms - ComboBox - Fill From ArrayList


Let's see how to fill our ordinary windows forms combobox control with an arraylist of data.

We then see display a messagebox when our combobox items are seected.

Example Demo

What is a ComboBox

A combobox is a User Interface control that displays items in a dropdown menu.

ComboBoxes allow users to select one item at a time.

Why ComboBox?

No. Advantage
1. ComboBox display lists of items in a small space.
2. ComboBox allow users to select one item at a time.
3. ComboBox allows us to handle IndexSelectionChanged events.

Let's go.

1. Create Empty Project

  1. Open up Visual Studio and proceed over to File --> New Project

  2. A new dialog popus up like this:

Create Project

  1. Give our empty project a name and click OK. An empty project will get generated for us.

2. Make project a Windows Project

Just right click on your project choose properties and set output type to Windows Application:

MetroFramewok References

3. Progam.cs

Create a class Program.cs. It is our main class with our main method. This is the only class we have.

using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;

namespace ComboBoxArrayList
{
    static class Program
    {
        private static ComboBox comboBox;
        public static void Main()
        {
            Form myForm = new Form
            {
                Text = "WinForms ComboBox - ArrayList",
                ClientSize = new Size(564, 420)
            };

            comboBox = new ComboBox { Location = new Point(164, 176),DropDownStyle = ComboBoxStyle.DropDownList};
            ArrayList nebulae = new ArrayList { "Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Helix", "Rosette", "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Witch Head", "Bumerang" };
            comboBox.DataSource = nebulae;

            comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;

            myForm.Controls.Add(comboBox);
            Application.Run(myForm);
        }

        static void comboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show(comboBox.SelectedItem.ToString());
        }
    }
}

Best Regards, Oclemy.

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. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post