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?
- WPF has one great feature for that. Its called "Databinding". For starting with WPF this should help you.Andre– Andre2012-08-09 07:04:29 +00:00Commented Aug 9, 2012 at 7:04
- 1ahem.. WinForms had data binding too :)LadderLogic– LadderLogic2012-08-09 07:31:11 +00:00Commented Aug 9, 2012 at 7:31
- 3I don't mention the opposite. I just said that WPFs Databinding is a great Feature :)Andre– Andre2012-08-09 08:10:41 +00:00Commented Aug 9, 2012 at 8:10
7 Answers
CASE 1 - You don't have a data-source:
You can just populate the ComboBox with static values as follows -
- from XAML:
<ComboBox Height="23" Name="comboBox1" Width="120"> <ComboBoxItem Content="Alice"/> <ComboBoxItem Content="Bob"/> <ComboBoxItem Content="Charlie"/> </ComboBox> - from CodeBehind - 1:
private void Window_Loaded(object sender, RoutedEventArgs e) { comboBox1.Items.Add("Alice"); comboBox1.Items.Add("Bob"); comboBox1.Items.Add("Charlie"); } - 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 -
- bind the
ItemsSourceproperty inXAMLto the data-source like -
<!-- MyDataSource is an IEnumerable type property in ViewModel --> <ComboBox Height="23" Width="120" ItemsSource="{Binding MyDataSource}" /> - assign data-source to the
ItemsSourceproperty 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
- You should use an
ObservableCollection<T>as the data-source - You should bind the
ItemsSourceproperty inXAMLto the data-source (as shown above) - You can assign data-source to the
ItemsSourceproperty 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>.
Comments
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
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
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
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
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 :)