0

I have a windows forms; and there are several controls on it.
I want to have them in a foreach loop to call each control's Clear() method, to make it clear and re-initiliazed item.

How can I do it?**

When I wath the formpage on debug-mode of Vs 2008, I see the "this" thus I can see all of them inside it..

.net version: 2.0

4
  • 2
    Which Control has a .Clear()-Method? Commented Oct 28, 2011 at 8:25
  • If you see it in the debugger, you should be able to use it in code, especially with the help of IntelliSense. Commented Oct 28, 2011 at 8:28
  • @ the NumberEntry whic is derived from text box control on our team project Commented Oct 28, 2011 at 8:29
  • @jv42 I know I can do it that way, but I am curious if I get them all in a loop to call Clear method, which is common for all objects in "this" form. Commented Oct 28, 2011 at 8:30

3 Answers 3

2

You might have controls on controls on controls etc. So it might be a good idea to put Dmitry Erokhin's code in a recursive function:

private void ClearNumberEntries(ControlCollection controls) { foreach (Control ctrl in controls) { if (ctrl is NumberEntry) { ((NumberEntry)ctrl).Clear(); } //if you are sure a NumberEntry can never have child controls that could also be of type NumberEntry you can put this in an else in stead ClearNumberEntries(ctrl.Controls); } } 
Sign up to request clarification or add additional context in comments.

Comments

1

You could iterate through controls like this:

foreach (Control ctrl in this.Controls) { if (ctrl is NumberEntry) { ((NumberEntry)ctrl).Clear(); } } 

Comments

0

for initializing controls again no need to clear each controls, just clear controls in form and call InitializeComponent()

 private void InitializeControls() { this.Controls.Clear(); InitializeComponent(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.