In my previous blog WPF Combo Box we saw how to create simple combo box and combo box items in XAML. Here we will see how to add combo box items from code behind (.cs) file
<Window x:Class="ComboBoxDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Name="CountryLabel" Content="Country" Grid.Row="0" Grid.Column="0" Height ="25" Margin="5"></Label>
<ComboBox Name="CountryComboBox" Grid.Row="0" Grid.Column="1" Height="25" Width="100" Margin="5">
</ComboBox>
</Grid>
</Window>
.cs file
1. By calling method LoadComboBoxData.
namespace ComboBoxDemo
{
/// <summary>
/// Interaction logic for
MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CountryComboBox.ItemsSource =
LoadComboBoxData();
}
private string[] LoadComboBoxData()
{
var array = new[] {"Austria", "Belgium", "China", "Germany", "India", "Norway"};
return array;
}
}
}
2. directly adding items in the comboBox
namespace ComboBoxDemo
namespace ComboBoxDemo
{
/// <summary>
/// Interaction logic for
MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CountryComboBox.Items.Add("Austria");
CountryComboBox.Items.Add("Belgium");
CountryComboBox.Items.Add("China");
CountryComboBox.Items.Add("Germany");
CountryComboBox.Items.Add("India");
CountryComboBox.Items.Add("Norway");
}
}
}
Output: