Monday, September 1, 2008

Locate nested controls easily

Finding controls within a Page's control hierarchy can be painful but if you know how the controls are nested you can use the lesser known "$" shortcut to find controls without having to write recursive code. The following example shows how to use the DefaultFocus property to set the focus on a textbox that is nested inside of a FormView control. Notice that the "$" is used to delimit the nesting: 

<form id="form1" runat="server" DefaultFocus="formVw$txtName">
  <div>

  <asp:FormView ID="formVw" runat="server">
  <ItemTemplate>

  Name: 
  <asp:TextBox ID="txtName" runat="server" 

  Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />
  </ItemTemplate>

  </asp:FormView>

  </div>
</form> 

This little trick can also be used on the server-side when calling FindControl().
Here's an example: 

TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox;

if (tb != null)

{
  //Access TextBox control

No comments: