服务器控件HtmlTable下控件赋值问题
在程序开发过程中,碰到这样的问题:
1<table>
2 <tr>
3 <td><asp:DropDownList id=dropdownlist1 runat=server></td>
4 </tr>
5</table>
在基类页中有如下代码:2 <tr>
3 <td><asp:DropDownList id=dropdownlist1 runat=server></td>
4 </tr>
5</table>
1foreach(Control pagectl in Page.Controls[1].Controls )
2 {
3 if (pagectl is DropDownList)
4 {(pagectl as DropDownList).Item.add();
5 ……
6 }
7}
如上能正常执行,但当把table转成服务器控件时,DropDownList下拉框中的内容总为空,跟踪调试后发现系统根本就没有找到DropDownList控件。其原因是DropDownList控件在HtmlTable下,找到HtmlTable但不会找其下面的控件。2 {
3 if (pagectl is DropDownList)
4 {(pagectl as DropDownList).Item.add();
5 ……
6 }
7}
改后代码如下:
1foreach(Control pagectl in Page.Controls[1].Controls )
2 {
3 if (pagectl is System.Web .UI .HtmlControls .HtmlTable )
4 {
5 foreach(HtmlTableRow row in (pagectl as HtmlTable).Rows )
6 {
7 foreach(HtmlTableCell cell in row.Cells )
8 {
9 if (cell.Controls .Count !=0 && cell.Controls [0] is DropDownList )
10 {
11 (cell.Controls [0] as DropDownList ).Items .Add ("5");
12 }
13 }
14 }
15 }
执行后,又能正常运行。 2 {
3 if (pagectl is System.Web .UI .HtmlControls .HtmlTable )
4 {
5 foreach(HtmlTableRow row in (pagectl as HtmlTable).Rows )
6 {
7 foreach(HtmlTableCell cell in row.Cells )
8 {
9 if (cell.Controls .Count !=0 && cell.Controls [0] is DropDownList )
10 {
11 (cell.Controls [0] as DropDownList ).Items .Add ("5");
12 }
13 }
14 }
15 }
附:递归方法列举页面所有控件,包括某些控件中的子控件,如上面所说服务器表
格控件下 的子控件:
代码:
1private void Button1_Click(object sender, System.EventArgs e)
2 {
3 DisplayControl(this.Page );
4 }
5
6 public void DisplayControl(Control sender)
7 {
8 foreach(Control con in sender.Controls)
9 {
10 this.Response .Write (con.GetType ().ToString ()+" "+con.UniqueID .ToString ());
11 this.Response .Write ("<br>");
12 DisplayControl(con);
13 }
14 }
2 {
3 DisplayControl(this.Page );
4 }
5
6 public void DisplayControl(Control sender)
7 {
8 foreach(Control con in sender.Controls)
9 {
10 this.Response .Write (con.GetType ().ToString ()+" "+con.UniqueID .ToString ());
11 this.Response .Write ("<br>");
12 DisplayControl(con);
13 }
14 }