Monday, May 4, 2009

Using FindControl to find your control that is inside a FormView control.

The FindControl method is overloaded. So, be sure you are using the one you want to. The page object has one, but that will only find controls that are at the page level. This means that nothing in a container, or data control such as a FormView will be found by this method, unless you give it the path to the control.

Here is the simple example of a TextBox at the Page level.

<asp:TextBox ID="TextBox1"runat="server" />

To find the control from the C# code behind, you would do something like this.

TextBox tb = Page.FindControl("TextBox1") as TextBox;

Now for an example where the same TextBox is in the FormView control.

<asp:FormView ID="FormView1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server" />

Here is how you would find that same control if it was in a FormView control.

TextBox tb = Page.FindControl("FormView1$TextBox1") as TextBox;

The above line of code only works if the FormView1 control is directly on the page and NOT in some other container. Also, TextBox1 can’t be in a container that is inside of FormView1. If you have additional containers, delimit them with ‘$’.

I recommend saving yourself a bit of headache and use the overloaded FindControl that FormView provides. This way, the path is relative to FormView1 at least. Less dependency on where the controls are placed on the page is good in my book.

TextBox tb = FormView1.FindControl("TextBox1") as TextBox;

The FindControl is nice, but it is NOT recursive. However, this gives you the code to search recursively. There is a bit of a performance penalty (theoretically), so I can’t recommend it. Though, there are likely some cases where you don’t know where the control is on the page or if it is nested in a container, etc, so this kind of strategy might be necessary. Use with care. :)


1 comment:

Anonymous said...

Why didn't you postthe code here too?! That link is dead now :(