0

I have a combo box which I want the default value to be -- Select Gender --

I have tried the following coding, and I got this error

Items collection must be empty before using ItemsSource.

Please help

cboGender.ItemsSource = null;
cboGender.DisplayMemberPath = "Display";
cboGender.SelectedValuePath = "Value";
cboGender.SetBinding(ComboBox.ItemsSourceProperty, oBinding);
cboGender.Items.Insert(0, "--Select Gender--");
cboGender.SelectedIndex = 0;
Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • What if you set the property like this - `Text="--Select Gender--"` and remove this line `cboGender.Items.Insert(0, "--Select Gender--");` – Krishnraj Rana Sep 29 '14 at 11:20
  • possible duplicate of [How to display default text "--Select Team --" in combo box on pageload in WPF?](http://stackoverflow.com/questions/1426050/how-to-display-default-text-select-team-in-combo-box-on-pageload-in-wpf) – Andrey Korneyev Sep 29 '14 at 11:26
  • Why are you binding and inserting directly? – paparazzo Sep 29 '14 at 12:57

3 Answers3

0

Add "--Select Gender--" to your Collection before binding it to the ItemsSource (if you want it as first, remember to use Insert(0, ) and then after binding it, set the SelectedIndex to it.

Saverio Terracciano
  • 3,885
  • 1
  • 30
  • 42
0

May be you should try to call

cboGender.Items.Clear();

before the insertion of the default item.

OR

Just create your data source with the default value item before inserting any value in the combo box and write something like this:

cboGender.Items.Clear();
cboGender.ItemsSource = dataSource;

where dataSource would be the list with the all items.

Dilyan Dimitrov
  • 789
  • 1
  • 7
  • 24
0

You can use

<ComboBox x:Name="cboGender"
 Text="--Select Gender--" />

if you don't need to choose this default value again after first selection