C# WPF – ComboBox – Fill From an Array

How to create a WPF(Windows Presentation Foundation) application with a combobox that we then populate from an array.

In this tutorial we want to see how to create a WPF(Windows Presentation Foundation) application with a combobox that we then populate from an array.

If the user selects an item we show the selected item in a messagebox.

What is Windows Presentation Foundation?

Windows Presentation Foundation (WPF) is a platform for creating and running visually rich .NET applicatios.
WPF was created by Microrosft and targets .NET platform.

WPF has two compositions:

  1. A rich set of DLLs(Dynamic Link Libraries) designed for creating Windows applications that have rich visual user interfaces and extensive data binding.
  2. A public Application Programming Interface (API), allowing our programs to
    access those DLLs and use their powerful capabilities

We have a YouTube Channel By the Way

So if you prefer video tutorial check here:

What is XAML ?

XAML is an XML-based markup language for specifying and setting the characteristics of classes.
Most WPF programs use both C# and XAML. C# being the programming language while XAML being the user interface markup language.

Through XAML we specify mainly the static and visual aspects of the user interface.

Mostly we don't have to write XAML from scratch as we can use the designer which can generate for use elegant XAML that we can then edit to our liking.

Let's Create and Fill A WPF ComboBox from Array

So let's jump to our example. We want to create a simple app with a combobox that is filled from a String array.

Add ComboBox To XAML

We will start by adding our ComboBox to XAML and registering an event handler that will be triggered when our WPF ComboBox control selectionIndex changes.

        <ComboBox x:Name="myComboBox" HorizontalAlignment="Left" Margin="125,154,0,0" VerticalAlignment="Top" Width="269" SelectionChanged="myComboBox_SelectionChanged"/>
        <Label Content="Modern Spiritual Teachers" HorizontalAlignment="Left" Margin="117,45,0,0" VerticalAlignment="Top" Width="277" FontWeight="Bold" FontSize="20"/>

Move Over to MainWindows.xaml.cs

We will have some System.Windows and System.Windows.Controls namespaces specified via the using directive.

Also we will have our namespace and partial class that inherits from Window.

using System.Windows;
using System.Windows.Controls;

namespace MrComboBox
{
    public partial class MainWindow : Window{}
}

Create Data Source and Set it To ComboBox

We will create a readonly string array and set it as the data source property of our ComboBox.

We will also set the first item as the selected item in our combobox using the selectedIndex property.

        private readonly string[] spiritualTeachers = {"Rumi","Sri Ramana Maharshi","Master Eckhart","Jiddu Krishnamurti","Osho","Eckhart Tolle","Allan Watts","Sadhguru","Anthony De Mello","Rupert Spira","Leo Gura"};
        private bool windowShowFirstTime = true;
        private void populateWPFComboBox()
        {
            myComboBox.ItemsSource = spiritualTeachers;
            myComboBox.SelectedIndex = 0;
        }

Get and Display Selected Item

We will create our event handler which will be handling the selectedIndexChanged event.

In the process we will get that selected item and show it in a message box.

        private void myComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (windowShowFirstTime)
            {
                windowShowFirstTime = false;
                return;
            }
            MessageBox.Show(myComboBox.SelectedItem.ToString(), "Spiritual Teacher",MessageBoxButton.OK,MessageBoxImage.Information);
        }

Well here are our complete source codes.

MainWindow.xaml

Here's our Xaml code:

<Window x:Class="MrComboBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="C# WPF ComboBox - Fill From Array" Height="350" Width="525">
    <Grid>
        <ComboBox x:Name="myComboBox" HorizontalAlignment="Left" Margin="125,154,0,0" VerticalAlignment="Top" Width="269" SelectionChanged="myComboBox_SelectionChanged"/>
        <Label Content="Modern Spiritual Teachers" HorizontalAlignment="Left" Margin="117,45,0,0" VerticalAlignment="Top" Width="277" FontWeight="Bold" FontSize="20"/>

    </Grid>
</Window>

MainWindow.xaml.cs

Here's our C# code:

using System.Windows;
using System.Windows.Controls;

namespace MrComboBox
{
    public partial class MainWindow : Window
    {
        private readonly string[] spiritualTeachers = {"Rumi","Sri Ramana Maharshi","Master Eckhart","Jiddu Krishnamurti","Osho","Eckhart Tolle","Allan Watts","Sadhguru","Anthony De Mello","Rupert Spira","Leo Gura"};
        private bool windowShowFirstTime = true;
        private void populateWPFComboBox()
        {
            myComboBox.ItemsSource = spiritualTeachers;
            myComboBox.SelectedIndex = 0;
        }
        private void myComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (windowShowFirstTime)
            {
                windowShowFirstTime = false;
                return;
            }
            MessageBox.Show(myComboBox.SelectedItem.ToString(), "Spiritual Teacher",MessageBoxButton.OK,MessageBoxImage.Information);
        }
        public MainWindow()
        {
            InitializeComponent();
            populateWPFComboBox();
        }

    }
}

Result

C# WPF ComboBox

C# WPF ComboBox

Best Regards.

Leave a Reply

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