Hi all!

I'm trying to create a function that will allow me to set the properties of all the specified controls in my form at once.

In a more direct example: I'm trying to change the text of every textbox in my form to null ("" would do fine to, I don't care).

I'm using the following code for this:

foreach(TextBox tb in this.Controls)
            if(tb != null)
                tb.Text = null;

The problem is that this gives me an error reporting that it can't cast System.Windows.Controls.PictureBox to S.W.C.Textbox... Though there are Pictureboxes in the form, I haven't asked to change those in any way I can see...

Anybody have an idea how I can fix this?

I've also tried using typeof() but I couldn't figure out how to use it since the example I had was in VB and used typeof(tb) but that wouldn't work in C#

Thanks for reading.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

If you'll notice, you specify "this.Controls". Those controls contain all of the controls on your form, not just the TextBox-es. You need to check the type of each control as you iterate over it, to make sure it's a TextBox.

Something like:

foreach (Control c in this.Controls)
    if (c.GetType().ToString() == "System.Windows.Forms.TextBox")
        ((TextBox)c).Text = "";

Thank you VERY mcriscolo!!

I changed it a bit though, I used the typeof(Textbox) comparison myself, seems more logic and easier to read. (For me that is ;))

Thanks for the help! And even more for pointing out my mistake!

Use the extension method System.Linq.Enumerable.OfType<TResult>:

foreach(TextBox tb in this.Controls.OfType<TextBox>())
    tb.Text = "";
This question has already been answered. Start a new discussion instead.