C# Windows Forms – ComboBox – Fill From Array

In this class we see how to populate a windows forms combobox control from a string of data. We then handle ItemSelectionChanged events and display the selected item in a messagebox.

This is a pure ComboBox control without any third party library.

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.

ComboBox is a public class defined in the assembly System.Windows.Forms.dll and belongs to System.Windows.Forms namespace.

The default index for ComboBox is the SelectdeIndexChanged event. ComboBox is a ComVisible class.

ComboBox class derives from System.Windows.Forms.ListControl class, just like it's sister ListBox.

ComboBox provides us a default public empty constructor.

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.

There are normally two ways of creating windows user interface in C#:

  1. Using Windows Designer to Drag Drop controls.
  2. Creating Windows Controls programmatically.

We'll use the latter approach.

Advnatages of Creating Windows Forms UI Controls Programmatically

No. Advantage
1. It gives us full control of our source code. There is no source magically generated for us hence we feel we have total confidence in our code.
2. It is the best way to learn how things work. It's easy to get addicted addicted to using the Windows Forms Designet but doing things programmatically allows see how each and every line works. This is the best way to learn us we are able to respect more the code we write than that generated for us magically by some tool. Moreover we can tinker with stuff and see what works and what doesn't.
3. It heavily reduces the amount of code we have to write and the number of classes and files we have. Instead of having to create partial classes, we can simply have one single class that's suitable for what we have to do and write some clean code inside it.
4. It's very easy and more enjoyable than drag dropping controls.
5. It's also infinitely better for us teachers to express what line by line what we want to share. This is because we don't have to spend alot of valuable time instructing users of the lots of assumptions we've made of what they should do. Instead we can just show them how to create a project,add references and then copy and paste code in their class and edit it. It allows us go straight to the code without alot of bluff and instructions.

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

First we add our imports:

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

The System namespace will give us access to a String object and an EventArgs object . The String object will be the data type for our Form's Text property. An EventArgs object on the other hand will be passed to our event handler.

The System.Drawing namespace will give access to the Size structure property of the Form and the Point object property of the ComboBox.

The System.Windows.Forms namespace will give us access to the Form,ComboBox and Application references.

Then we specify our namespace:

namespace ComboBoxArray
{
    ...
}

Then create a static class inside it.

static class Program
{
    .....
}

We'll have one static field: a ComboBox reference:

private static ComboBox comboBox;

Being static implies that it belongs to the class as opposed to the class instance.

We'll then have one main method: Main():

public static void Main(){..}

Inside our Main() method we'll instantiate a System.Windows.Forms.Form control:

Form myForm = new Form()..

Take note that we are creating windows controls programmatically as opposed to just drag dropping them using windows designer. This allows us to move line by line and have full control of our code.

We then set the form properties using the Object Initializer Syntax.

Form myForm = new Form()
{
    Text = "WinForms ComboBox - Array",
    ClientSize = new Size(564, 420),
};

The Text property will allows us set the title of the Form while the ClientSize it's Size.

We then instantiate our ComboBox setting it's properties as well :

 comboBox = new ComboBox { Location = new Point(164, 176) ,DropDownStyle = ComboBoxStyle.DropDownList};

The Location will set the ComboBox's location by assigning it a Point object with x and y cordinates passed as parameters. The DropDownStyle will set our ComboBox DropDown style. In this case we use DropDownList which makes our ComboBox Text not editable and displayed in a dropdown list-like manner. Other options could be Simple and DropDown.

We then create our string array with our data:

String[] nebulae = {..}

This is our data source. So we set the array as our DataSource property of our ComboBox:

 comboBox.DataSource = nebulae;

We then create our event handler:

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

When the ComboBox is selected we will be displaying a messagebox with the selected item. You can see that we use comboBox.SelectedItem to obtain the selected object and cast it to a string using the ToString() method.

Inside our Main() method we will add our ComboBox control into our Form's Controls property, then run the application:

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

Here's the full code:

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

namespace ComboBoxArray
{
    static class Program
    {

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

            comboBox = new ComboBox { Location = new Point(164, 176) ,DropDownStyle = ComboBoxStyle.DropDownList};
            String[] nebulae = 
            {
                "Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Elephant's Trunk", "Helix", "Rosette","Snake","Bernad 68",
                "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Cone", "Flame", "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 *