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?

edit
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.

Recommended Answers

All 3 Replies

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 = "";
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.