2009-09-28 91 views
3

我有一個在tr/td中有幾個文本框的formview。我試圖通過使用.FindControl方法來獲取文本框,但它返回null。 FormView始終處於編輯模式(所以我總是在EditItemTemplate中),我試圖將查詢字符串值加載到來自上一頁的文本框中,所以我確實需要在page_load上發生這種情況。我做這在GridView的所有這樣的時候:FormView.FindControl():對象引用錯誤

txtFirstName = (TextBox)fvGeneralInfo.FindControl("txtFirstName"); 

或像這樣:

txtFirstName = (TextBox)fvGeneralInfo.FooterRow.FindControl("txtFirstName"); 

或像這樣:

txtFirstName = (TextBox)fvGeneralInfo.Rows.FindControl("txtFirstName"); 

是怎麼回事?

<asp:FormView ID="fvGeneralInfo" runat="server" 
    DataSourceID="objInstructorDetails" 
    OnItemCommand="fvGeneralInfo_ItemCommand" 
    OnItemUpdated="fvGeneralInfo_ItemUpdated" 
    DefaultMode="Edit" 
    DataKeyNames="InstructorID" > 
    <EditItemTemplate> 
     <table> 
      <tr> 
       <td colspan="2" class="Admin-SubHeading" style="padding-left:10px;">General Info:</td> 
      </tr> 
      <tr> 
       <td class="Admin-FieldLabel">ID:</td> 
       <td><asp:TextBox ID="txtInstructorId" runat="server" CssClass="Admin-Textbox" ReadOnly="true" Text='<%# Bind("InstructorID") %>' /></td> 
      </tr> 
      <tr> 
       <td class="Admin-FieldLabel">First Name:</td> 
       <td><asp:Textbox ID="txtFirstName" runat="server" CssClass="Admin-Textbox" Text='<%# Bind("FirstName") %>' /></td> 
      </tr> 
      </table> 
     </EditItemTemplate> 
    </asp:FormView> 
+0

難道你沒發現任何答案是正確的? – abatishchev 2011-11-25 21:06:50

回答

2

先致電DataBind();。然後FindControl()

2

abatishchev的答案是正確的,雖然我發現這個變體有點整齊:它避免了必須顯式調用DataBind()。

<asp:FormView ID="fvMember" runat="server" DataSourceID="tblMembers" DefaultMode="Insert" OnDataBound="DataBound">...</asp:FormView> 

protected void DataBound(object sender, EventArgs e) 
{ 
    if (fvMember.CurrentMode == FormViewMode.Edit) 
    { 
     Label lblSubmit = fvMember.FindControl("lblSubmit") as Label; 
     ... 
    } 
}