0

Hello.
I'm writing Windows Form App and I found "tiny" trouble. I can't manage with finding control by a name.

I have this code:

private Control FindByName(string name)
        {
            foreach (Control c in this.Controls)
            {
                if (c.Name == name)
                    return c;
            }
            return null;
        }

and simply it doesn't return me what I want.

I have on my form TextBox named "diamond".

The code:

Control tb = FindControlByName("diamond");
                    tb.Text = "...";

returns me an exception: NullReferenceException.
Moreover I don't have method "AppendText" which is specific to TextBox.

What's wrong?

4
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by ddanbe
1

Your code looks good.
I think your form can has few containers like Tabs, Group box or something like that. It means you need to find your control in the every container.
Cheers

0

Rogachev is correct, if your controls contain any controls, you must check those as well. It's fairly straightforward to set up a basic recursive algorithm. To make it more efficient, however, would be more challenging :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.