Reputation: 3252
I have a ComboBox in WPF whose ItemsSource is set to a list programmatically. How would I go about clearing the selection in an event handler? I've tried:
comboBox.SelectedIndex = -1;
comboBox.SelectedItem = null;
comboBox.SelectedValue = null;
comboBox.SelectedValue = "";
None of them have any effect.
Upvotes: 20
Views: 33123
Reputation: 13
Really old question, but here's what you can do if you are data binding from View Model and don't want to interact with the code-behind.
If the Combobox item source is a List<string>
and the selected item is string
, then simply set the binded selected item variable to null
, notify change, then set to String.Empty
.
Upvotes: 0
Reputation: 1
first, you must do this in the selectionchange function
private void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (combobox.SelectedIndex == -1)
{
combobox.SelectedIndex.ToString();
}
else
{
string datacombo=(combobox.SelectedValue.ToString());
}
}
after that use it anywhere combobox.SelectedIndex=-1. now I am using another combobox to select on selection change
private void cbocombobox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
combobox.SelectedValue=null;
combobox.SelectedIndex = -1;
}
and it worked for me alhamdulillah
Upvotes: 0
Reputation: 46
ComboBox.SelectedIndex = -1 did not work for me, perhaps because I am using a custom ControlTemplate in a custom ComboBox?? Anyway, reseting the ItemsSource does work. I am calling this from a Behavior.
var items = comboBox.ItemsSource;
comboBox.ItemsSource = null;
comboBox.ItemsSource = items;
Upvotes: 0
Reputation: 1
In the following example I show the way it worked for me, this for a ComboBox from a user control:
Combobox in the usercontrol:
<ComboBox x:Name="OFFSE_INI_CMBX" HorizontalAlignment="Left" Margin="26,106,0,0" VerticalAlignment="Top" Height="20" Width="100" DropDownClosed="OFFSE_INI_CMBX_DropDownClosed">
<ComboBoxItem x:Name="NV" Content=" NV" ToolTip="Sub Command Tooltip 1" Height="20" Selected="NV_Selected"></ComboBoxItem>
</ComboBox>
Function that works
private void OFFSE_INI_CMBX_DropDownClosed(object sender, EventArgs e)
{
this.OFFSE_INI_CMBX.SelectedIndex = -1;
this.OFFSE_INI_CMBX.Text = "";
}
Upvotes: 0
Reputation: 219
I want to clear the ComboBox
in DropDownClosed
event of another ComboBox
. Therefore I used following code inside of first ComboBox
DropDownClosed
event
private void comboBox1_DropDownClosed(object sender, EventArgs e)
{
this.comboBox.ItemsSource = null;
}
Upvotes: 1
Reputation: 60003
comboBox.SelectedIndex = -1;
works for me.
Are you doing anything else in your event handler? Are you using databinding?
Upvotes: 33
Reputation: 41
I found that I needed to also add:
comboBox.Text = "";
to get the text to clear
Upvotes: 4
Reputation: 41620
comboBox.SelectedIndex = -1;
Is the way to go. I don't know why it doesn't work for you; perhaps an event handler for SelectedIndexChanged
changes the value?
Upvotes: 5