|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
How to: Locate Child Controls by ID in an ASP.NET Web Page
You can get a reference to a specific control using a method that searches its naming container for the control's ID.
To locate a control by ID
Call themethod of the naming container, passing it a string containing the ID of the control you want to use. The method returns an object of type that you can cast to the appropriate type.
The following code example shows how you can locate a specific control. The sample is a handler for the Click event of a button in acontrol. When the button is clicked, the code searches for a control named
Label1in the current GridView item, which is the control's naming container. If the control is found, its text is displayed in a second Label control named
LabelTextelsewhere on the page.
Protected Sub GridView1_ItemCommand(ByVal source As Object, _ ByVal e As GridViewCommandEventArgs) _ Handles GridView1.ItemCommand Dim l As Label l = CType(e.Item.FindControl("Label1"), Label) If (Not l Is Nothing) Then LabelText.Text = l.Text End If End Sub