How to clear comboBoxes

  • Thread starter Thread starter Keith Smith
  • Start date Start date
K

Keith Smith

Is there an easier way to clear all of the comboBoxes on my form? I am
currently using this code...

autoCompleteComboBox1.Text="";
autoCompleteComboBox1.SelectedText="";

autoCompleteComboBox2.Text="";
autoCompleteComboBox2.SelectedText="";

autoCompleteComboBox3.Text="";
autoCompleteComboBox3.SelectedText="";

autoCompleteComboBox4.Text="";
autoCompleteComboBox4.SelectedText="";

autoCompleteComboBox5.Text="";
autoCompleteComboBox5.SelectedText="";

autoCompleteComboBox6.Text="";
autoCompleteComboBox6.SelectedText="";


.....But it would be nice if I could do something like this:

AllControls.Clear;
 
Sorry, this is in VB code and I don't know the for each equivalent off the
top of my head.

For Each ctl In Form.Controls
If TypeOf ctl Is ComboBox Then
ct1.Text = ""
ct1.SelectedText = ""
End If
Next
 
[In VB:]
For Each ctl In Form.Controls
If TypeOf ctl Is ComboBox Then
ct1.Text = ""
ct1.SelectedText = ""
End If
Next

I have tried but can't seem to find the proper C# code. The closest I can
come up with is...

foreach(Control x in Form1)
{
}

Which obviously is not complete. Any ideas?
 
Keith Smith said:
foreach(Control x in Form1)

How about this?

foreach (Control c in Form1.Controls)
{
if (c is ComboBox) { c.Clear(); }
}

(The Clear method actually removes all the items from the list. You
might just want to clear the Text property. Obviously, you can do what
you like with c inside that block.)

P.
 
Uh, so I need to check my code before I post it!

foreach (Control c in this.Controls)
{
if (c is ComboBox)
{
((ComboBox) c).Items.Clear(); // or .Text = "", or whatever
}
}

P.
 
Back
Top