FindControl looks for controls in incorrect template of FormView

有些话、适合烂在心里 提交于 2019-12-23 19:30:26

问题


How do you locate controls from the codebehind when switching modes in a FormView? It looks like you can't use FindControl during the Page_Load event, since it will be searching for controls in the previously shown template rather than the newly selected one. I suspect you can't rely on the PageLoad alone but have to find controls within another event, like OnDataBound, but should you really HAVE to do that? I've seen several formviews in my day that lack events like OnDataBound...

More details about my specific case: I've got a formview where both the ItemTemplate, InsertItemTemplate and EditItemTemplate contain the same textbox. (it's got the same ID in all templates)

During the Page_Load event I use FindControl to locate the textbox and change it's visibility. Works perfectly fine when initially loading the formview, but for some reason it doesn't work when the form is changing modes/changing templates (after the page has rendered you see that the textbox visibility is incorrect)

For instance switching from read to edit mode - the formview.Mode will be set to FormViewMode.Edit, but when using FindControl during the PageLoad event it will search for controls within the ItemTemplate rather than the EditItemTemplate. Thus, if you have a control with the same ID in all templates it will find the control within the incorrect template, and after the page has loaded you'll be extremely confused as to why the control that's loaded doesn't have the same properties as you thought it when you examined it in the debugger during the pageLoad.


回答1:


Don't use Page_Load to bind or access your FormView, instead use the FormView's DataBound event and the CurrentMode property:

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
    }
}


来源:https://stackoverflow.com/questions/18852878/findcontrol-looks-for-controls-in-incorrect-template-of-formview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!