FormView.FindControl(): object reference error

2019-01-26 19:22发布

问题:

I have a formview that has several textboxes inside of tr/td's. I'm trying to get the textboxes by using the .FindControl method but it's coming back null. The FormView is always in Edit mode (so I'm always in the EditItemTemplate) and i'm trying to load querystring values into the textboxes coming from the previous page so I do need this to happen on page_load. I do this on Gridviews all the time like this:

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

or like this:

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

or like this:

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

What gives?

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

回答1:

Call DataBind(); first. Then FindControl()



回答2:

abatishchev's answer is right, although I found this variation a bit neater: it avoids having to call DataBind() explicitly.

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