The FindControl method of the System.Web.UI.Control class appears simple enough to use. In fact, the MSDN description of the method is one simple sentence:
Searches the current naming container for the specified server control.
The key to using FindControl is to invoke the method on the correct container. As a warm up, let’s say we have the following form inside of an aspx page.
Although we can declare a member variable in our code behind class to reference TextBox1, let’s use the FindControl method in an event handler.
The above code will find TextBox1 and write a message into the response stream. But what happens when the TextBox is not a child of the control we query with FindControl? Consider the following form.
In the above form, the parent of TextBox1 is the Panel control Panel1. Let’s use the same event handler we used in the first example and see what happens.
Once again we have easily located the control. For later comparison, let’s view an excerpt of the HTML source the ASP.NET form has given us.
In the source above we can see ASP.NET has given the TextBox a client side ID of TextBox1, the same ID we use on the server. This behavior changes when we place the textbox inside of a control implementing the INamingContainer interface, which will change the way we use the FindControl method. Any control implementing INamingContainer will create a new control namespace so that all child controls will have a unique ID on the page. In short, an INamingContainer control will guarantee there are no naming conflicts on a page. This behavior is best demonstrated with an example.
FindControl in a DataGrid
There are several ASP.NET controls which implement INamingContainer, including the DataGrid, the Repeater, and the DataList. Let’s build a form with a DataGrid and view the HTML output.
The DataGrid in the form will display data from a well known SQL Server table. Using a TemplateColumn, we will add a TextBox control with the ID of TextBox1 to each row of the grid. Let’s take a look at an excerpt of the HTML ASP.NET generates.
Here we can see there are many instances of TextBox1, but each ID is prefixed with some additional identifier information. This behavior shows the INamingContainer objects at work. The DataGrid implements INamingContainer and will preface each child control ID with ‘DataGrid1’. As we will see shortly, a DataGrid uses a collection of DataGridItem controls to represent each row of data. A DataGridItem control also implements INamingContainer, and will preface the name of child controls with a it’s own generated identifier (‘_ctrl2’, ‘_ctrl3’, etc.).
Now, if we used the following code, FindControl will return a null value
The Page control cannot find a TextBox1 because the TextBox controls hide themselves inside of INamingContainer controls. Besides, which control would we really expect FindControl to return? The first TextBox control of the page? The last TextBox control? Typically, when you want to find a TextBox inside of a DataGrid, you’ll be looking for a TextBox on a specific row the user has chosen. For example, we added a Select column to allow the user to click on a hyperlink to chose the selected row. Let’s try to grab the TextBox control in the SelectedIndexChanged event.
The code invokes FindControl on the selected DataGridItem object. The code above will work, as demonstrated in the following figure.
We have also added some additional output to clearly see the chain of ownership leading to our TextBox. The TextBox1 control has a TableCell object as a parent, which in turn is a child control of a DataGridItem object, and so on up the line until we reach a Page control. The code to produce this dump is next.
The code will walk up the Parent control references building a string of control IDs (when a control ID exists – not all controls in a form will have a server side ID), and the control type.
We also added an EditCommandColumn to our DataGrid for the user to select a row to edit. Working with the EditCommand event handler is slightly easier, because the second parameter to the handler is of type DataGridCommandEventArgs, which contains a reference to the DataGridItem the user has selected for interaction.
Finding Controls In Headers and Footers
For some DataGrid objects you may want to display an interactive control inside of the header or footer section. These cases require a slightly different method of attack with FindControl. Consider the following form
Here we have added a DropDownList control into the HeaderTemplate and FooterTemplate of the DataGrid. We should know at this point we cannot call FindControl on the Page, or on the DataGrid to retrieve these controls, because they will exist inside of another INamingContainer control, specifically a DataGridItem. What might be suprising however, is how we cannot use the DataGrid object’s Items collection as we did earlier. MSDN documentation has the following to say about the Items collection.
Note: Only items bound to the data source are contained in the Items collection. The header, footer, and separator are not included in the collection.
So we will not find the header and footer DataGridItem controls inside the Items collection, but all child controls must exist inside the Controls collection. In this case, our earlier dump of the DataGrid control hierarchy will prove useful. We know the parent of each DataGridItem is a DataGridTable, and the parent of the DataGridTable is the DataGrid control itself. We will have to assume the DataGridTable is the first control in the DataGrid, and the header row will be the first control of the DataGridTable (consequently the footer is the last control of the DataGridTable). Thus the following code:
will give us both DropDownList controls in the header and footer, and produce the following output.
Seeing hard coded index values into the Controls collection is a bit worrisome. If your control changes, or the DataGrid control changes in a newer version of the framework, this code could break. An alternate solution could involve looping through the DataGridTable controls looking for DataGridItem objects with a ItemType property equal to ListItem.Header or ListItem.Footer. Whichever you decide, neither feels extremely robust in the face of future changes.
FindControl in Repeater controls
Like the DataGrid, the Repeater is an INamingContainer. Let’s take a look at the following form which displays authors from SQL Server.
Each row of the repeater will contain a TextBox and Button control. Every Button control will use the same event handler where we can grab the corresponding TextBox control in the row with the following code.
Here you can see we have taken a different tack by asking for the parent of the Button control which has fired the event handler. In the following screen shot, you can see the parent of the TextBox (and the Button) is a RepeaterItem control (which also implements INamingContainer). Thus the first TextBox appearing on the screen will have an unique ID of Repeater1:_ctl0:TextBox1.
One more tip before we move to the last section. Suppose we added a second button at the bottom of the form with the repeater. When the user clicks this button we want to loop the repeater collecting the contents of each TextBox control from every row. You can accomplish this task with the following code.
User Controls
For the sake of completeness, let’s take a look at how FindControl works when a User Control (ascx) appears. Let’s through the following user control into a form.
If we view the HTML output, we will see the following.
Although user controls do not implement INamingContainer, they do ensure their child controls will not have a naming conflict. For instance, if we placed two of these user controls on the same form, without munging the names we would have two TextBox1 controls on the same form.
Although you generally will not need to do this, you can find a control from the code behind of a user control as easily as the first example in this article
If you wanted to find the TextBox control from inside of the parent page (not recommended, but here for completeness), you would have to invoke FindControl on the user control. In the following example, we will also use FindControl to find our user control.
Conclusion
Hopefully this article has shed some light and will offer some assistance to those readers who have lost wayward controls. The behavior of FindControl makes perfect sense once you understand the purpose of INamingContainer and begin using FindControl on the correct objects.
0
收藏
推荐专栏更多
猜你喜欢
无刷新更改包含UpdatePanel的ajaxtoolkit:TabPanel 的 HeaderText属性
.Net后台使用RegisterClientScriptBlock和RegisterStartupScript调用前台的JS 区别
关于usr/bin/ld: cannot find -lxxx问题总结
linux下使用find xargs grep查找文件及文件内容
Java调用https服务报错unable to find valid certification path to requested target的解决方法
VS.Net 2005 中文正式版下载
/usr/bin/ld: cannot find -l* 错误的解决方法……
使用phpize建立php扩展 Cannot find config.m4.
make报错:"/usr/bin/ld: cannot find -lXXX"
Log4Net使用详解(续)
杂七杂八(1)——如何查看本机的.NET Framework版本
大型软件公司.net面试题!一定得看(附答案)
ASPNetCore MVC ModelValidation-ajax
C#如何设置Excel文档保护——工作簿、工作表、单元格
在.NET数据库访问方面的Dapper类库介绍
C#/VB.NET 如何添加、获取、删除PDF附件
C#/VB.NET 创建PDF项目符号列表和多级编号列表
C# /VB.NET 操作Word (一)——插入、修改、删除Word批注
C# 操作Excel数据透视表
微信支付---APP调起微信支付c#后台接口
扫一扫,领取大礼包
转载于:https://blog.51cto.com/loveu/38263
Ctrl+Enter 发布
发布
取消