populating a text box with FindControl

Stuart picture Stuart · Aug 8, 2013 · Viewed 14.9k times · Source

I have multiple textboxes and I want to programatically populate them with the same method.

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>    
    <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="500">
        <ProgressTemplate>
            <div id="FreezeUpdate" class="FreezePaneOn">
               <div id="InnerFreezePane" class="InnerFreezePane gradient"><asp:Literal ID="litProgress" runat="server" Text="<%$ Resources:LocalizedText, freezeMsg_ProcessingPleaseWait %>"></asp:Literal></style></div>
            </div>
        </ProgressTemplate>
    </asp:UpdateProgress>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <asp:TextBox ID="tbxCollectionAddress" runat="server" TextMode="MultiLine" ReadOnly="True" CssClass="address"></asp:TextBox>
        <asp:TextBox ID="tbxReturnAddress" runat="server" TextMode="MultiLine" ReadOnly="True" CssClass="address"></asp:TextBox>
    </asp:UpdatePanel>
</asp:Content>

then the method...

protected void PopulateAddress(string txtTextbox, Address adrAddress)
    {
        TextBox txtAddress = (TextBox)FindControl(txtTextbox);

        txtAddress.Text = "Hello World";

    }

when I call this method like below...

PopulateAddress("tbxReturnAddress", CollectionAddress);

...I get exception...

System.NullReferenceException: Object reference not set to an instance of an object.

...and it highlights the txtAddress.Text = "Hello World"; line.

I'd like to do it like this with the method because there are three separate addresses that I need to populate on the form but I'd like to try using re-usable code to do it by feeding in the address object and the textbox id, but I'm falling over just at the findcontrol stage.

What am I missing?

Answer

zey picture zey · Aug 8, 2013

Firstly , test your function likes

  TextBox txtAddress = (TextBox)FindControl("tbxReturnAddress");

or

You can try likes this ,

  TextBox txtAddress = (TextBox)Page.FindControl("tbxReturnAddress");

Edit

If your text-box is in the UpdatePanel ,

  TextBox txtAddress = (TextBox)UpdatePanel1.FindControl("tbxReturnAddress");