C# Windows Forms – ComboBox – Fill From Generic List

 

In this class we see how to populate a C# winodws forms combobox control with a generic list.

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

This is our only class.

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

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

            comboBox = new ComboBox { Location = new Point(164, 176), DropDownStyle = ComboBoxStyle.DropDownList };
            List<string> nebulae = new List<string> { "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.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *