日期:2014-05-18  浏览次数:20355 次

请问Page.FindControl找不到GridView是怎么回事儿?其他控件都能找到
GridView的ID为   dtg_search,里面的模版列有一个按钮   ID为btn_edit

我希望对这个按钮进行一下属性的修改   可是现在连dtg_search都找不到

顺便说一下,这个代码段是放在其类里面的   我重写了OnLoadComplete方法
                protected   override   void   OnLoadComplete(System.EventArgs   e)
                {
                        SetPageByUserAuthorization();
                }
SetPageByUserAuthorization()里面就是这个代码段:

Control     ctl_tmp   =   Page.FindControl( "dtg_search ");
          if   (ctl_tmp   !=   null)
                {
                        Control   ctl   =   ((GridView)ctl_tmp).FindControl( "btn_edit ");
                              if   (ctl   !=   null)
                                {
                                        btn_edit_common   =   ((Button)ctl);
                                }
                }

------解决方案--------------------
1.
Web Control 开发中(Page 其实是 Control),如果你重载基类方法(如引发事件的方法,这是里 OnLoadComplete ),请一定要调用基类的方法,特别当你无法确定基类实现细节的时候,否则可能发生不可预期的错误
等你熟悉 asp.net 页生命周期、控件周期以及控件开发细节,你会自然明白

2.
Control ctl_tmp = Page.FindControl( "dtg_search ");
-------------------
当你调用此代码的时候, 此GridView是否已经添加到页面上?
你可以直接查看 Page.Controls 检查其中是否存在此GridView

3.
Control ctl = ((GridView)ctl_tmp).FindControl( "btn_edit ");
-------------------------
这样是不正确的!!!!
你的 btn_edit 存在于 GridViewRow 中,而不是直接属于 GridView ,但 GridViewRow 的命名容器是 GridView
正确用法大概是,在 GridView 的每一行中查找,

foreach(GridViewRow r in MyGridView.Rows) {
Button btnEdit = r.FindControl( "myButton ") as Button;
btnEdit.Text = "click me, plz ";
// more codes ...
}


4.
关于 Control.FindControl(string id) 的使用,你一定要知道 "命名容器 " (Control.NamingContainer ) 的概念,这是一个层次结构

Control.FindControl(string id) 方法直接在当前 NamingContainer 查找目标控件

具体请参卡 MSDN:
http://msdn2.microsoft.com/zh-cn/library/system.web.ui.control.findcontrol(VS.80).aspx
http://msdn2.microsoft.com/zh-cn/library/system.web.ui.control.namingcontainer(VS.80).aspx


Hope helpful!