45

When I have added a comboBox to the WPF window, how do I add items to the comboBox? Int the XAML code for the design or in NameOfWindow.xaml.cs file?

3
  • WPF has one great feature for that. Its called "Databinding". For starting with WPF this should help you. Commented Aug 9, 2012 at 7:04
  • 1
    ahem.. WinForms had data binding too :) Commented Aug 9, 2012 at 7:31
  • 3
    I don't mention the opposite. I just said that WPFs Databinding is a great Feature :) Commented Aug 9, 2012 at 8:10

7 Answers 7

79

CASE 1 - You don't have a data-source:

You can just populate the ComboBox with static values as follows -

  1. from XAML:
<ComboBox Height="23" Name="comboBox1" Width="120"> <ComboBoxItem Content="Alice"/> <ComboBoxItem Content="Bob"/> <ComboBoxItem Content="Charlie"/> </ComboBox> 
  1. from CodeBehind - 1:
private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.Items.Add("Alice"); comboBox1.Items.Add("Bob"); comboBox1.Items.Add("Charlie"); } 
  1. from CodeBehind - 2:
// insert item at specified index of populated ComboBox private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.Items.Insert(2, "Alice"); comboBox1.Items.Insert(5, "Bob"); comboBox1.Items.Insert(8, "Charlie"); } 

CASE 2 - You have a data-source, and the items never get changed:

You can use the data-source to populate the ComboBox. Any IEnumerable type can be used as a data-source. You can -

  1. bind the ItemsSource property in XAML to the data-source like -
<!-- MyDataSource is an IEnumerable type property in ViewModel --> <ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" /> 
  1. assign data-source to the ItemsSource property in the code-behind, like -
private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.ItemsSource = new List<string> { "Alice", "Bob", "Charlie" }; } 

CASE 3 - You have a data-source, and the items might get changed

  1. You should use an ObservableCollection<T> as the data-source
  2. You should bind the ItemsSource property in XAML to the data-source (as shown above)
  3. You can assign data-source to the ItemsSource property in the code-behind (as shown above)

Using an ObservableCollection<T> ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI. It's up to you how you populate the ObservableCollection<T>.

Sign up to request clarification or add additional context in comments.

Comments

41

Its better to build ObservableCollection and take advantage of it

public ObservableCollection<string> list = new ObservableCollection<string>(); list.Add("a"); list.Add("b"); list.Add("c"); this.cbx.ItemsSource = list; 

cbx is comobobox name

Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged

Comments

12

Use this

string[] str = new string[] {"Foo", "Bar"}; myComboBox.ItemsSource = str; myComboBox.SelectedIndex = 0; 

OR

foreach (string s in str) myComboBox.Items.Add(s); myComboBox.SelectedIndex = 0; 

3 Comments

Nice it's working well! But if I want like name or a headline for the combobox like "Your options:", then I guess I just add that first in the array, but when a selection is made, I check so that index 0 isn't activated!? Or is there a better way?
No, I get "your options" twice!? It's on the "button" but it's also in the list that drops down hen I click on the combobox!
Is there a way to solve this? I want a name on the button and when I press on the button, I want items to be drop down, and not the name of the button? Preciate if this could be done!
4

You can fill it from XAML or from .cs. There are few ways to fill controls with data. It would be best for You to read more about WPF technology, it allows to do many things in many ways, depending on Your needs. It's more important to choose method based on Your project needs. You can start here. It's an easy article about creating combobox, and filling it with some data.

Comments

1

I think comboBox1.Items.Add("X"); will add string to ComboBox, instead of ComboBoxItem.

The right solution is

ComboBoxItem item = new ComboBoxItem(); item.Content = "A"; comboBox1.Items.Add(item); 

Comments

0

There are many ways to perform this task. Here is a simple one:

<Window x:Class="WPF_Demo1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="TestWindow" Title="MainWindow" Height="500" Width="773"> <DockPanel LastChildFill="False"> <StackPanel DockPanel.Dock="Top" Background="Red" Margin="2"> <StackPanel Orientation="Horizontal" x:Name="spTopNav"> <ComboBox x:Name="cboBox1" MinWidth="120"> <!-- Notice we have used x:Name to identify the object that we want to operate upon.--> <!-- <ComboBoxItem Content="X"/> <ComboBoxItem Content="Y"/> <ComboBoxItem Content="Z"/> --> </ComboBox> </StackPanel> </StackPanel> <StackPanel DockPanel.Dock="Bottom" Background="Orange" Margin="2"> <StackPanel Orientation="Horizontal" x:Name="spBottomNav"> </StackPanel> <TextBlock Height="30" Foreground="White">Left Docked StackPanel 2</TextBlock> </StackPanel> <StackPanel MinWidth="200" DockPanel.Dock="Left" Background="Teal" Margin="2" x:Name="StackPanelLeft"> <TextBlock Foreground="White">Bottom Docked StackPanel Left</TextBlock> </StackPanel> <StackPanel DockPanel.Dock="Right" Background="Yellow" MinWidth="150" Margin="2" x:Name="StackPanelRight"></StackPanel> <Button Content="Button" Height="410" VerticalAlignment="Top" Width="75" x:Name="myButton" Click="myButton_Click"/> </DockPanel> </Window> 

Next, we have the C# code:

 private void myButton_Click(object sender, RoutedEventArgs e) { ComboBoxItem cboBoxItem = new ComboBoxItem(); // Create example instance of our desired type. Type type1 = cboBoxItem.GetType(); object cboBoxItemInstance = Activator.CreateInstance(type1); // Construct an instance of that type. for (int i = 0; i < 12; i++) { string newName = "stringExample" + i.ToString(); // Generate the objects from our list of strings. ComboBoxItem item = this.CreateComboBoxItem((ComboBoxItem)cboBoxItemInstance, "nameExample_" + newName, newName); cboBox1.Items.Add(item); // Add each newly constructed item to our NAMED combobox. } } private ComboBoxItem CreateComboBoxItem(ComboBoxItem myCbo, string content, string name) { Type type1 = myCbo.GetType(); ComboBoxItem instance = (ComboBoxItem)Activator.CreateInstance(type1); // Here, we're using reflection to get and set the properties of the type. PropertyInfo Content = instance.GetType().GetProperty("Content", BindingFlags.Public | BindingFlags.Instance); PropertyInfo Name = instance.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance); this.SetProperty<ComboBoxItem, String>(Content, instance, content); this.SetProperty<ComboBoxItem, String>(Name, instance, name); return instance; //PropertyInfo prop = type.GetProperties(rb1); } 

Note: This is using reflection. If you'd like to learn more about the basics of reflection and why you might want to use it, this is a great introductory article:

If you'd like to learn more about how you might use reflection with WPF specifically, here are some resources:

And if you want to massively speed up the performance of reflection, it's best to use IL to do that, like this:

Comments

-1

With OleDBConnection -> connect to Oracle

OleDbConnection con = new OleDbConnection(); con.ConnectionString = "Provider=MSDAORA;Data Source=oracle;Persist Security Info=True;User ID=system;Password=**********;Unicode=True"; OleDbCommand comd1 = new OleDbCommand("select name from table", con); OleDbDataReader DR = comd1.ExecuteReader(); while (DR.Read()) { comboBox_delete.Items.Add(DR[0]); } con.Close(); 

That's all :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.