Kuntady Nithesh
Kuntady Nithesh

Reputation: 11731

How to addComboBox Items dynamically in wpf

I am new to WPF ,

I am adding items dynamically to a combobox like below

   objComboBox.Items.Add("<--Select-->");

Now i need to set value & index for the particular item . In asp.net i was doing

DropDownList1.Items.FindByText("<--Select-->").Value ="-1" 

I ma not finding appropriate method in wpf . how can iI do this?

Upvotes: 5

Views: 26579

Answers (4)

Toody
Toody

Reputation: 87

If it's first in the list you should use: objComboBox.SelectedIndex = 0; or DropDownList1.SelectedIndex = 0;

If it's not the first then use: objComboBox.SelectedItem = "<--Select-->"; or DropDownList1.SelectedItem = "<--Select-->";

Upvotes: 0

Tigran
Tigran

Reputation: 62276

Always try to avoid accessing the UI directly. Use a binding to bind data to your control and add, search, remove whatever... only on data. To change a UI will take care of WPF binding itself.

An example: http://www.codeproject.com/KB/WPF/DataBindingWithComboBoxes.aspx

Upvotes: 4

Haris Hasan
Haris Hasan

Reputation: 30097

  combo.SelectedIndex = combo.Items.IndexOf("<--Select-->");

But better way is to use Binding as mentioned by snurre

Upvotes: 1

snurre
snurre

Reputation: 3105

XAML:

<ComboBox ItemsSource="{Binding cbItems}" SelectedItem="{Binding SelectedcbItem}"/>

Code-behind:

public ObservableCollection<ComboBoxItem> cbItems { get; set; }
public ComboBoxItem SelectedcbItem { get; set; }

public MainWindow()
{
    InitializeComponent();
    DataContext = this;

    cbItems = new ObservableCollection<ComboBoxItem>();
    var cbItem = new ComboBoxItem { Content = "<--Select-->" };
    SelectedcbItem = cbItem;
    cbItems.Add(cbItem);
    cbItems.Add(new ComboBoxItem { Content = "Option 1" });
    cbItems.Add(new ComboBoxItem { Content = "Option 2"});
}

Upvotes: 19

Related Questions