Web Forms Server Controls Programming Web Forms Server Controls Accessing Server Controls Programmatically
You can get a reference to a specific control using a method that searches its naming container for the control’s ID.
- Call the FindControl method 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 Control 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 a GridView control. When the button is clicked, the code searches for a control named Label1 in the current GridView item, which is the Label control’s naming container. If the control is found, its text is displayed in a second Label control named LabelText elsewhere on the page.
protected void GridView1_ItemCommand ( object source, GridViewCommandEventArgs e ) {
Label l;
l = ( Label ) e.Item.FindControl ( "Label1" );
if ! ( l == null ) {
LabelText.Text = l.Text;
}
}
Protected Sub GridView1_ItemCommand ( ByVal source As Object, ByVal e As GridViewCommandEventArgs )
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 |
|
C# |
VB |
Using the Controls Collection Accessing a Control’s Naming Container