How to Bind a Struct to a ComboBox in C#

Often times when you need to load a structure (struct) member to a ComboBox or DropDownList so that the user can select a value, and based on the selection, the resulting value will be applied.

In one of my WPF applications, I needed to load all PixelFormats structure members (properties) in a ComboBox. Then, based on the selection of the PixelFormats, I would change the output of the image.

We can use the Type class to read type members, including methods, properties, and other type members. A struct has some properties. As you can see from the following code snippet, I create a Type object from the PixelFormats by using typeof keyword. Once a Type is created, I can use the GetProperties method to get all properties of a struct.

The Type.The GetProperties method returns an array of PropertyInfo. The Name property of the PropertyInfo object gives us the name of the property.

Once we have an array of PropertyInto objects, we can loop through the properties and add them to a ComboBox one by one.

The following code snippet loads all members of the PixelFormats struct to a ComboBox in WPF.

private void LoadPixelFormatsToComboBox()
{
    PixelFormatsList.Items.Clear();
    //Type t = typeof(System.Windows.Media.PixelFormats);
    //PropertyInfo[] props = t.GetProperties();
    foreach (PropertyInfo prop in 
typeof(System.Windows.Media.PixelFormats).GetProperties())
    {
        PixelFormatsList.Items.Add(prop.Name);
    }
    PixelFormatsList.SelectedIndex = 0;
}

You can use the same approach to bind a struct to a Windows Forms or ASP.NET ComboBox or DropDownList controls.

Summary

In this post and code example, we learned how to bind a struct to a combo box in C#.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.