Search code examples
asp.netnestedformview

Nested FormView controls


I have an asp.net form that looks something like this...

<asp:Panel ID="PanelForm" runat="server" >
    <asp:FormView ID="FormView1" runat="server" >
        <asp:EditItemTemplate>
            <asp:FormView ID="FormView2" runat="server" >
                <InsertItemTemplate>
                    <asp:TextBox ID="myControl" runat="server" />
                </InsertItemTemplate>
            </asp:FormView>
        </asp:EditItemTemplate>
    </asp:FormView>
</asp:Panel>

I want to set the text of a TextBox called "myControl" to "myText".

The code below results in t = null which throws an "Object reference not set to an instance of an object." error.

FormView fv2 = (FormView)FormView1.FindControl("FormView2");
fv2.ChangeMode(FormViewMode.Insert);
TextBox t = (TextBox)fv2.FindControl("myControl");
t.Text = "myText";

How to update this TextBox from the code behind?


Solution

  • I was missing a DataBind()...

    FormView fv2 = (FormView)FormView1.FindControl("FormView2");
    fv2.ChangeMode(FormViewMode.Insert);
    fv2.DataBind();
    TextBox t = (TextBox)(fv2.FindControl("myControl"));
    t.Text = "myText";  
    

    Doh!