In this class we see how to populate a C# winodws forms combobox control with a generic list.
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
- Open up Visual Studio and proceed over to File --> New Project
- A new dialog popus up like this:
- 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:
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.