2011-05-05 51 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"; 
     } 
    } 
    } 
}