Reputation: 1300
I am trying to create a method that will clear all of the ComboBoxes
on my window. This is what I have tried so far:
private void ClearAllComboboxes(ComboBox cmb)
{
cmb.SelectedIndex = -1;
}
And then I call the method like below, but I can only insert one ComboBox
to clear at a time.
private void btnClearAll_Click(object sender, RoutedEventArgs e)
{
ClearAllComboboxes(cmbBarlocks);
}
So what I am trying to do is clear all of the comboboxes with as little coding as possible. Can someone please tell me how and what would be the best possible way to do this? Thank you :)
Upvotes: 1
Views: 304
Reputation: 1221
I assume that you are using MVVM and you have SelectedItem property for every combobox in your viewmodel. In viewmodel, you can just set SelectedItem=null for each combobox. It will clear your combobox selection.
If you are not using MVVM, then you can use following code in code behind:
private void ClearAllComboboxes()
{
List<ComboBox> comboBoxes = new List<ComboBox>();
GetLogicalChildCollection<ComboBox>(container, comboBoxes);
comboBoxes.ForEach(combobox => combobox.SelectedIndex = -1);
}
private static void GetLogicalChildCollection<T>(DependencyObject parent,List<T> logicalCollection) where T : DependencyObject
{
var children = LogicalTreeHelper.GetChildren(parent);
foreach (object child in children)
{
if (child is DependencyObject)
{
DependencyObject depChild = child as DependencyObject;
if (child is T)
{
logicalCollection.Add(child as T);
}
GetLogicalChildCollection(depChild, logicalCollection);
}
}
}
Upvotes: 1
Reputation: 759
In your handler try this, it worked when I had a similar issue with ListBox
void ClearCombos(params ComboxBox[] boxes)
{
foreach(var box in boxes)
box.ItemsSource = null;
}
and call it ClearCombos(x,y,z); where x,y,z are the boxes you want to clear
Upvotes: 0
Reputation: 147
protected void btnAll_Click(object sender, EventArgs e)
{
ClearInputs(Page.Controls);
}
//For Clear All Control Values
void ClearInputs(ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is ComboBox )
((ComboBox )ctrl).ClearSelection();
ClearInputs(ctrl.Controls);
}
}
Upvotes: 0
Reputation: 29006
Let me assume All your comboboxes
are inside a container(let it be stackPanel
), the you can set selected index to -1 for all of them using the following snippet:
foreach (Control ctrl in stkContainer.Children)
{
if (ctrl.GetType() == typeof(ComboBox))
{
ComboBox cbo = ctrl as ComboBox;
ClearAllComboboxes(cbo);
}
}
If you want to clear the combobox means you have to re-define your method signature as:
private void ClearAllComboboxes(ComboBox cmb)
{
cmb.Items.Clear();
}
Upvotes: 0