Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

c# - FormView.FindControl(): object reference error

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...