ASP.NET: What is the function of FindControl method?
Asked on ASP.NET Forums
What is the function of FindControl method?
To return the control instance which has given ID. Every control has FindControl method since its available in System.Web.UI.Control class.
FindControl works in two ways, it can take in the local ID of the control (exactly as is given to ID attribute on aspx) when it looks for the control in the current naming container. Other way is to give UniqueID of the control to FindControl method, when control is located deeper in the naming hierarchies (for example in a GridView), when FindControl resolves the control from there and returns reference to it.
For example, you have a TextBox on Page.
<asp:TextBox ID="TextBox1" runat="server" />
You could reference it in code:
Dim tb As TextBox = CType(Page.FindControl("TextBox1"), TextBox)
In practise this is obsolete code, since control on Page level has member automatically (in ASP.NET 2.0 in any case, in ASP.NEt 1.x in inline code and in codebehind with explicit member declaration) but would work. Just typing TextBox1.xxx, where xxx stands for the member of the TextBox type, would also work.
Other example is having TextBox in a FormView as FormView is a naming container (implements INamingContainer) which essentially means that FormView provides its own naming scope for its child controls. It is important to note that by default FindControl locates controls from the current naming scope. So to look from FormView's naming scope, you run FindControl against FormView instance.
<asp:FormView ID="FormView1" runat="server" DefaultMode="ReadOnly" >
<asp:TextBox ID="TextBox1" runat="server" Text="Text in TextBox" />
<asp:Button ID="Button1" runat="server" Text="Let's look for the TB" />
And code for it:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Looking from FormView's naming scope - FormView implements INamingContainer
Dim tb As TextBox = CType(FormView1.FindControl("TextBox1"), TextBox)
'Method 2. UniqueID - rendered as name attribute in markup - in this case running from Page works
tb = CType(Page.FindControl("FormView1$TextBox1"), TextBox)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'Dummy binding tom FormView to make it build control hierarchy
Dim arr As New ArrayList()
FormView1.DataSource = arr
In either of cases, TextBox is found within FormView and it's Text is printed on output