2011-05-05 68 views
4

我有一个带有内部控件的项目模板的窗体视图,是否可以访问该控件OnDatabound,以便我可以将控件与数据绑定。我在这里用一个面板作为例子。FormView ItemTemplate中的ASP.net访问控制

<cc1:LOEDFormView ID="FireFormView" runat="server" DataSourceID="DataSourceResults"  CssClass="EditForm" DataKeyNames="id" OnDatabound="FireFromView_Databound"> 
<ItemTemplate> 

<asp:Panel ID ="pnl" runat="server"></asp:Panel> 

</ItemTemplate> 

</cc1:LOEDFormView> 

回答

9

你要照顾的项目模式,以及在你的控制存在,你想找到。就像如果你的项目模板控制,那么它会像..

if (FormView1.CurrentMode == FormViewMode.ReadOnly) 
{ 

    Panel pnl = (Panel)FormView1.FindControl("pnl"); 
} 
+0

试过这个,控件仍然是空的 – Funky 2011-05-06 08:01:57

+2

确保formview有行数据绑定,否则它将始终为空。检查您的选择语句和参数以及 – irfandar 2012-10-20 17:07:12

+0

我想在OnDataBound事件方法中找到控件。它仍然是空的。 我通过调试发现它不是空,当我从任何位置(page_load等)手动调用FormView.DataBind()。但是,当SqlDataSource通过SqlDataSourceID属性自动绑定时,OnDataBound中的FormView中不存在任何控件。荒谬。关于要废弃这整个事情,只是使用没有减速的剃须刀mvc。 – Barry 2017-09-21 14:42:47

1

我在标记中看不到标签,但看到一个面板。因此,要访问面板,

尝试

Panel p = FireFormView.FindControl("pnl") as Panel; 
if(p != null) 
{ 
    ... 
} 
0
if (FireFormView.Row != null) 
    { 
     if (FireFormView.CurrentMode == FormViewMode.ReadOnly) 
     { 
      Panel pnl = (Panel)FireFormView.FindControl("pnl"); 
     } 
     else 
     { 
      //FormView is not in readonly mode 
     } 
    } 
    else 
    { 
     //formview not databound, check select statement and parameters. 
    } 
0

下面这段代码解决了我的问题。尽管该示例访问了一个标签,但它适用于大多数控件。您只需将DataBound事件添加到您的FormView

protected void FormView1_DataBound(object sender, EventArgs e) 
{ 
    //check the formview mode 
    if (FormView1.CurrentMode == FormViewMode.ReadOnly) 
    { 
    //Check the RowType to where the Control is placed 
    if (FormView1.Row.RowType == DataControlRowType.DataRow) 
    { 
     Label label1 = (Label)UserProfileFormView.Row.Cells[0].FindControl("Label1"); 
     if (label1 != null) 
     { 
     label1.Text = "Your text"; 
     } 
    } 
    } 
}