3D-kreativ
3D-kreativ

Reputation: 9301

Add items to comboBox in WPF

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?

Upvotes: 45

Views: 213640

Answers (7)

atiyar
atiyar

Reputation: 8326

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>.

Upvotes: 77

devinbost
devinbost

Reputation: 5074

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:

Upvotes: 0

starko
starko

Reputation: 1149

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 :)

Upvotes: -1

jiasli
jiasli

Reputation: 9128

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);

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176886

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

Upvotes: 41

Varius
Varius

Reputation: 3407

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.

Upvotes: 4

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

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;      

Upvotes: 12

Related Questions