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?

Recommended Answers

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

Jump to Post

All 3 Replies

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

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 :)

Perhaps a look at this snippet may help also.

Be a part of the DaniWeb community

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