FindControl在FormView的错误模板中查找控件

Drk*_*ima 3 asp.net formview findcontrol

在FormView中切换模式时,如何从代码隐藏中找到控件? 看起来你不能在Page_Load事件期间使用FindControl,因为它将在先前显示的模板而不是新选择的模板中搜索控件.我怀疑你不能单独依赖PageLoad但是必须在另一个事件中找到控件,比如OnDataBound,但你真的应该这样做吗?我在我的日子里看过几个没有OnDataBound等事件的表单...

关于我的具体案例的更多细节: 我有一个formview,其中ItemTemplate,InsertItemTemplate和EditItemTemplate都包含相同的文本框.(它在所有模板中都有相同的ID)

在Page_Load事件期间,我使用FindControl来定位文本框并更改其可见性.在最初加载formview时工作得很好,但由于某种原因,当表单更改模式/更改模板时它不起作用(在页面呈现后,您看到文本框可见性不正确)

例如,从read模式切换到编辑模式 - formview.Mode将设置为FormViewMode.Edit,但在PageLoad事件期间使用FindControl时,它将搜索ItemTemplate中的控件而不是EditItemTemplate.因此,如果您在所有模板中都有一个具有相同ID的控件,它将在不正确的模板中找到该控件,并且在页面加载后,您将非常困惑为什么加载的控件不具有相同的属性正如你在pageLoad期间在调试器中检查它时所想的那样.

Tim*_*ter 5

不要Page_Load用来绑定或访问你的FormView,而是使用FormView's DataBound事件和CurrentMode属性:

protected void FormView1_DataBound(object sender, System.EventArgs e)
{
    if(FormView1.CurrentMode == FormViewMode.ReadOnly)
    {
        // here you can safely access the FormView's ItemTemplate and it's controls via FindControl
    }
    else if(FormView1.CurrentMode == FormViewMode.Edit)
    {
        // here  you can safely access the FormView's EditItemTemplate and it's controls via FindControl
    }
    else if(FormView1.CurrentMode == FormViewMode.Insert)
    {
        // here you can safely access the FormView's InsertItemTemplate and it's controls via FindControl
    }
}
Run Code Online (Sandbox Code Playgroud)