FormView.FindControl():对象引用错误

时间:2009-09-28 05:27:05

标签: c# asp.net .net formview findcontrol

我有一个在tr / td中有几个文本框的formview。我试图通过使用.FindControl方法获取文本框但它返回null。 FormView始终处于编辑模式(所以我总是在EditItemTemplate中),我正在尝试将查询字符串值加载到来自上一页的文本框中,所以我确实需要在page_load上进行此操作。我一直在Gridviews上这样做:

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>

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

首先致电DataBind();。然后FindControl()