When I was first starting out, I found the FindControl function to be very confusing.
Under what circumtances would I need to use this? How come sometimes Intellisense kicks in and recognizes the name of the control as you type it and other times you have to manually dig through the control hierarchy using the FindControl function?
From what I can figure out, if the control you want to manipulate is at the top level of the page (the Page object), Intellisense will detect it as you type. However, if the control you want to manipulate is in a Masterpage or other container, Intellisense can not dig through the hierarchy to find the control.
There are several posts about this issue out there, and some people have even written recursive FindControl functions that take some of the work out of it. Supposedly, such a function will have a performance hit, especially in complex hierarchies. So if you don't want to use this, here is an easy way to determine the full name of the control so you can get on on with your day:
As my project has evolved, the hierarchy of objects has necome more complex. I find myself using stacked FindControls to find my controls. For example, I am trying to programmatically reach the textbox control named txtClientName on my page. Here is the code I need to use for this:
Dim myClientName As TextBox = Page.Master.FindControl("MainContent").FindControl("Defectview1").FindControl("Formview1").FindControl("txtClientName")
myClientName.Text = "My new text is here!"
To determine your control's full hierarchy name, enable the Trace directive atop your page and then load it in a web browser. Example:
<%@ Page Title="" Language="VB" Trace="true" MasterPageFile="~/test/MasterPage.master" AutoEventWireup="false" CodeFile="findcontrol.aspx.vb" Inherits="test_findcontrol" %>
When the page loads in the browser, scroll down the page and find your control. You can use the browsers Find feature (Usually Control F) and type in the ID of the control. The ID was set in Visual Studio, "txtClientName" in my example. This textbox has the full control name, as determined by using "Trace=True".
ctl00$MainContent$Defectview1$FormView1$txtClientName
In order to programatically access that control, remember the FindControl line I am using is:
Dim myClientName As TextBox = Page.Master.FindControl("MainContent").FindControl("Defectview1").FindControl("Formview1").FindControl("txtClientName")
So each $ is a delimiter.
Note my FindControl starts with Page.Master while the control hierarcy actually begins with ctl00. Apaprently ctl00 is used by .NET to identify the Master Page. In my code I could have used ctl00 as my first step, but Page.Master is a shortcut.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment