FormView.FindControl(): object reference error

Tone picture Tone · Sep 28, 2009 · Viewed 11.9k times · Source

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>

Answer

Ed Graham picture Ed Graham · Nov 24, 2011

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