user2631662
user2631662

Reputation: 855

Clear a combobox in WPF

How do I clear a combobox in WPF? I have tried this code:

 private void btClear1_Click(object sender, RoutedEventArgs e)
    {

        txtID.Text = String.Empty;
        this.cbType.SelectedItem = -1;
    }

Upvotes: 5

Views: 22451

Answers (4)

Fred
Fred

Reputation: 5818

cbType.SelectedItem = -1 to clear the selection cbType.Items.Clear() to clear all the items

Upvotes: 5

vapcguy
vapcguy

Reputation: 7544

Totally clearing box items
For Googlers, since the title is misleading, if we were talking clearing the items from the box, I've seen several answers saying to use cbType.Items.Clear(). It depends on how the items were loaded. You could have hard-coded them into the XAML, added them with a function dynamically at runtime, used a type of databinding and/or loaded them to the .ItemSource. It will work for all but the latter case.

When you are using the .ItemSource to load the ComboBox via a DataTable's DefaultView, for example, you cannot simply do cbType.Items.Clear(). Since the method of populating the dropdown was not included in the question, I submit that for when you set the .ItemSource, you must do:

cbType.ItemsSource = null;

instead. Otherwise, if you try cbType.Items.Clear() you will get:

Operation is not valid while ItemSource is in use. Access and modify 
elements with ItemsControl.ItemsSource instead


Clearing the selected item
I went back and saw the OP's comment, saying the wish was to clear the selection, not the box. For that, the other answers stand:

cbType.SelectedIndex = -1;  
cbType.Text = "";  // I've found the first line does this for me, as far as appearances, but found other postings saying it's necessary - maybe they were using the property and it wasn't getting cleared, otherwise

Upvotes: 1

Sabareeshwari Kannan
Sabareeshwari Kannan

Reputation: 75

You can reset the combo box by binding in the XAML page.

For example, in that combobox field in the XAML page:

text={Binding viewmodelobject Name.property Name}

And then in ViewModelPage:

viewmodelobject Name.property Name="";

Upvotes: 3

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

To clear the selection set the SelectedIndex not the SelectedItem

cboType.SelectedIndex = -1;

You can set the SelectedItem or SelectedValue as well, but change it to null instead of -1 (these point to an object not an integer).

cboType.SelectedItem = null;

Upvotes: 4

Related Questions