asp.net - FindControl 在 FormView 的错误模板中查找控件

标签 asp.net formview findcontrol

在 FormView 中切换模式时如何从代码隐藏中定位控件? 看起来您无法在 Page_Load 事件期间使用 FindControl,因为它将在先前显示的模板而不是新选择的模板中搜索控件。 我怀疑您不能单独依赖 PageLoad,而必须在另一个事件中找到控件,例如 OnDataBound,但您真的必须这样做吗? 我曾经见过几个表单 View 缺少像 OnDataBound 这样的事件...

有关我的具体案例的更多详细信息: 我有一个表单 View ,其中 ItemTemplate、InsertItemTemplate 和 EditItemTemplate 都包含相同的文本框。 (所有模板中都有相同的 ID)

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

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

最佳答案

不要使用 Page_Load 绑定(bind)或访问 FormView,而是使用 FormViewDataBound事件和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
    }
}

关于asp.net - FindControl 在 FormView 的错误模板中查找控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18852878/

相关文章:

vb.net - Gridview RowUpdating 找不到控件

asp.net - 如何获取发起回发的 Updatepanel 的 id

c# - IIS 上的大量请求超时

asp.net - FindControl 如果从不同的类调用则不起作用

c# - 使用 EnableModelValidation 时如何验证 FormView 数据?

c# - 我如何将图像绑定(bind)到 <asp :Image/> tag in Form View

asp.net - 如何在 ASP.NET 页面上另一个用户控件的事件内查找 ASP.NET 页面的用户控件 编辑 : different content placeholders?

c# - 单击按钮时在 SqlDataSource 中运行存储过程

c# - 如何使用 ext.net 在 asp.net c# 中创建 Crystal 报表?

python - 返回到将您带到那里的页面 Django