Everyone gets there... the question is when...

There is this controls array, a property of the System.Windows.Forms.Form. All the controls that are in the form, are listed in the controls array and if you want to remove a particular control from the form, you just call the RemoveAt() method of the control array which will remove the control from the specified index.

Now I had a specific requirement where I was supposed to remove all the textboxes from the control array. So I ran a loop. If the control is a textbox, I would remove it else move on. But every time I call remove(), the indexes would be shuffled. So in case there are adjacent textboxes, I would miss some if I keep going in a sequence.

First thing that comes into my mind. Keep searching for textboxes in a loop until we are sure that there are no textboxes in the collection. For that every time you remove a textboxes, start the loop from zero by resetting the index to -1 (funny...!)

Second thing that comes into my mind. No need to go searching from 0 all you have to do is reduce your index by one and start searching again.

Then I realize I am going in the wrong direction. So I must think of a way where even if the index is being shuffled, it should not affect the sequence of operations.

So I loop through it backwards. Remove the last control first, and then come back. That would not disturb my previous indexes, and I would be able to remove them most efficiently.

Anyone can get to a simple solution like this. The important thing is how much time does he take?

No Comments