Share via


How to: Locate Controls by ID in an ASP.NET Web Page

When a control is not inside a naming container, you can get a reference to it by using the control's ID. When a control is inside a naming container, you must call a method that searches the naming container for the control's ID. A control might also be inside a naming container that you do not have direct access to.

To locate a control that is not inside a naming container

  • Reference the control's ID to access the object.

    The following example includes code that shows how to access a control that is not inside a naming container. The Label control named Message is not within a naming container and therefore can be accessed by ID.

    <%@ Page language="VB" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
      Sub Page_Load()
        Message.Text = String.Empty
      End Sub
    
      Sub ProductsListView_SelectedIndexChanging(ByVal sender As Object, ByVal e As ListViewSelectEventArgs)
    
        Dim item As ListViewItem = CType(ProductsListView.Items(e.NewSelectedIndex), ListViewItem)  
        Dim l As Label = CType(item.FindControl("DiscontinuedDateLabel"), Label)
    
        If String.IsNullOrEmpty(l.Text) Then
          Return
        End If
    
        Dim discontinued As DateTime = DateTime.Parse(l.Text)
        If discontinued < DateTime.Now Then      
          Message.Text = "You cannot select a discontinued item."
          e.Cancel = True
        End If
      End Sub
    
      Protected Sub ProductsListView_PagePropertiesChanging(ByVal sender As Object, _
                                                   ByVal e As PagePropertiesChangingEventArgs)
        ' Clears the selection.
        ProductsListView.SelectedIndex = -1
      End Sub
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
      <head id="Head1" runat="server">
        <title>ListView.SelectedIndexChanging Example</title>
      </head>
      <body>
        <form id="form1" runat="server">
    
          <h3>ListView.SelectedIndexChanging Example</h3>
    
          <asp:Label ID="Message"
            ForeColor="Red"          
            runat="server"/>
          <br/>
    
          <asp:ListView ID="ProductsListView" 
            DataSourceID="ProductsDataSource" 
            DataKeyNames="ProductID"
            OnSelectedIndexChanging="ProductsListView_SelectedIndexChanging" 
            OnPagePropertiesChanging="ProductsListView_PagePropertiesChanging"
            runat="server">
            <LayoutTemplate>
              <table cellpadding="2" runat="server" id="tblProducts" width="640px">
                <tr runat="server" id="itemPlaceholder" />
              </table>
    
              <asp:DataPager runat="server" ID="ProductsDataPager" PageSize="12">
                <Fields>
                  <asp:NextPreviousPagerField 
                    ShowFirstPageButton="true" ShowLastPageButton="true"
                    FirstPageText="|&lt;&lt; " LastPageText=" &gt;&gt;|"
                    NextPageText=" &gt; " PreviousPageText=" &lt; " />
                </Fields>
              </asp:DataPager>
            </LayoutTemplate>
            <ItemTemplate>
              <tr runat="server">
                <td valign="top">
                  <asp:LinkButton ID="SelectButton" runat="server" Text="..." CommandName="Select" />
                </td>
                <td valign="top">
                  <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
                </td>
                <td valign="top">
                  <asp:Label ID="ProductNumberLabel" runat="server" Text='<%#Eval("ProductNumber") %>' />
                </td>
                <td>
                  <asp:Label ID="DiscontinuedDateLabel" runat="server" Text='<%#Eval("DiscontinuedDate", "{0:d}") %>' />
                </td>
              </tr>
            </ItemTemplate>
            <SelectedItemTemplate>
              <tr runat="server" style="background-color:#ADD8E6">
                <td>&nbsp;</td>
                <td valign="top">
                  <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
                </td>
                <td valign="top">
                  <asp:Label ID="ProductNumberLabel" runat="server" Text='<%#Eval("ProductNumber") %>' />
                </td>
                <td>
                  <asp:Label ID="DiscontinuedDateLabel" runat="server" Text='<%#Eval("DiscontinuedDate", "{0:d}") %>' />
                </td>
              </tr>
            </SelectedItemTemplate>
          </asp:ListView>
    
          <asp:SqlDataSource ID="ProductsDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
            SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [DiscontinuedDate] 
              FROM Production.Product"
            UpdateCommand="UPDATE Production.Product
               SET Name = @Name, ProductNumber = @ProductNumber, DiscontinuedDate = @DiscontinuedDate
               WHERE ProductID = @ProductID">
          </asp:SqlDataSource>
    
        </form>
      </body>
    </html>
    
    <%@ Page language="C#" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
      void Page_Load()
      {
        Message.Text = String.Empty;
      }
    
      void ProductsListView_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
      {
        ListViewItem item = (ListViewItem)ProductsListView.Items[e.NewSelectedIndex];
        Label l = (Label)item.FindControl("DiscontinuedDateLabel");
    
        if (String.IsNullOrEmpty(l.Text))
        {
          return;
        }
    
        DateTime discontinued = DateTime.Parse(l.Text);
        if (discontinued < DateTime.Now)
        {
          Message.Text = "You cannot select a discontinued item.";
          e.Cancel = true;
        }
      }
    
      protected void ProductsListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
      {
        // Clear selection.
        ProductsListView.SelectedIndex = -1;
      }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
      <head id="Head1" runat="server">
        <title>ListView.SelectedIndexChanging Example</title>
      </head>
      <body>
        <form id="form1" runat="server">
    
          <h3>ListView.SelectedIndexChanging Example</h3>
    
          <asp:Label ID="Message"
            ForeColor="Red"          
            runat="server"/>
          <br/>
    
          <asp:ListView ID="ProductsListView" 
            DataSourceID="ProductsDataSource" 
            DataKeyNames="ProductID"
            OnSelectedIndexChanging="ProductsListView_SelectedIndexChanging"         
            OnPagePropertiesChanging="ProductsListView_PagePropertiesChanging"
            runat="server" >
            <LayoutTemplate>
              <table cellpadding="2" runat="server" id="tblProducts" width="640px">
                <tr runat="server" id="itemPlaceholder" />
              </table>
    
              <asp:DataPager runat="server" ID="ProductsDataPager" PageSize="12">
                <Fields>
                  <asp:NextPreviousPagerField 
                    ShowFirstPageButton="true" ShowLastPageButton="true"
                    FirstPageText="|&lt;&lt; " LastPageText=" &gt;&gt;|"
                    NextPageText=" &gt; " PreviousPageText=" &lt; " />
                </Fields>
              </asp:DataPager>
            </LayoutTemplate>
            <ItemTemplate>
              <tr runat="server">
                <td valign="top">
                  <asp:LinkButton ID="SelectButton" runat="server" Text="..." CommandName="Select" />
                </td>
                <td valign="top">
                  <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
                </td>
                <td valign="top">
                  <asp:Label ID="ProductNumberLabel" runat="server" Text='<%#Eval("ProductNumber") %>' />
                </td>
                <td>
                  <asp:Label ID="DiscontinuedDateLabel" runat="server" Text='<%#Eval("DiscontinuedDate", "{0:d}") %>' />
                </td>
              </tr>
            </ItemTemplate>
            <SelectedItemTemplate>
              <tr runat="server" style="background-color:#ADD8E6">
                <td>&nbsp;</td>
                <td valign="top">
                  <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
                </td>
                <td valign="top">
                  <asp:Label ID="ProductNumberLabel" runat="server" Text='<%#Eval("ProductNumber") %>' />
                </td>
                <td>
                  <asp:Label ID="DiscontinuedDateLabel" runat="server" Text='<%#Eval("DiscontinuedDate", "{0:d}") %>' />
                </td>
              </tr>
            </SelectedItemTemplate>
          </asp:ListView>
    
          <asp:SqlDataSource ID="ProductsDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
            SelectCommand="SELECT [ProductID], [Name], [ProductNumber], [DiscontinuedDate] 
              FROM Production.Product"
            UpdateCommand="UPDATE Production.Product
               SET Name = @Name, ProductNumber = @ProductNumber, DiscontinuedDate = @DiscontinuedDate
               WHERE ProductID = @ProductID">
          </asp:SqlDataSource>
    
        </form>
      </body>
    </html>
    

To locate a control that is inside a naming container when you have a reference to the naming container

  • Call the FindControl method of the naming container, passing a string that contains the ID of the control that you want to use. The method returns an object of type Control that you must cast to the appropriate type.

    The example in the previous procedure also shows how you can access a control that is inside a naming container. The Label control named DiscontinuedDateLabel is inside a ListView control. Therefore, to access the Label control, you must call the FindControl method of the ListView control.

Locating a Control Inside a Hierarchy of Naming Containers

Sometimes, a control is inside a naming container but you do not have a reference to the naming container. In that case, one way to get a reference to the control is to write a custom method that searches the controls in a hierarchy of naming containers.

To locate a control by searching through a hierarchy of naming containers

  • Create a method that can be called recursively to search a naming control and its child naming containers.

    The following example shows one way to write a search method.

    Private Function FindControlRecursive(
        ByVal rootControl As Control, ByVal controlID As String) As Control
    
        If rootControl.ID = controlID Then
            Return rootControl
        End If
    
        For Each controlToSearch As Control In rootControl.Controls
            Dim controlToReturn As Control = 
                FindControlRecursive(controlToSearch, controlID)
            If controlToReturn IsNot Nothing Then
                Return controlToReturn
            End If
        Next
        Return Nothing
    End Function
    
    private Control FindControlRecursive(Control rootControl, string controlID)
    {
        if (rootControl.ID == controlID) return rootControl;
    
        foreach (Control controlToSearch in rootControl.Controls)
        {
            Control controlToReturn = 
                FindControlRecursive(controlToSearch, controlID);
            if (controlToReturn != null) return controlToReturn;
        }
        return null;
    }
    

    This method accepts a reference to a naming container. If you do not know which naming container on the page has the control that you are looking for, you can pass in the page itself as the top-level naming container. The method looks through all controls in the naming container that you pass to it. If it does not find the requested control, the method calls itself recursively for each lower-level naming container.

See Also

Concepts

Web Forms Control Identification