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?
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);
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
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:
Fast version of the ActivatorCreateInstance method using IL
Fast Dynamic Property and Field Accessors
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;
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 :)
Scenario 1 - you don't have a data-source for the items of the ComboBox
You can just populate the ComboBox with static values as follows -
From XAML:
<ComboBox Height="23" Name="comboBox1" Width="120">
<ComboBoxItem Content="X"/>
<ComboBoxItem Content="Y"/>
<ComboBoxItem Content="Z"/>
</ComboBox>
Or, from CodeBehind:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Add("X");
comboBox1.Items.Add("Y");
comboBox1.Items.Add("Z");
}
Scenario 2.a - 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 the data-source. You need to assign it to the ItemsSource property of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable
).
Scenario 2.b - you have a data-source, and the items might get changed
You should use an ObservableCollection<T> as the data-source and assign it to the ItemsSource property of the ComboBox (it's up to you how you populate the ObservableCollection<T>
). 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.