Search code examples
c#asp.netvisual-studio-2012visual-studio-2013code-behind

How to add asp:TextBox dynamically on code behind ? (Not TextArea)


This is a sample of one asp:TextBox

  <asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
        <ContentTemplate>
            <asp:TextBox runat="server" ID="MyBox"  />
        </ContentTemplate>
    </asp:UpdatePanel>

In the code behind I get a lot of data from the DB , and I want to create accordingly asp:TextBox text-boxes .

Is it possible to add the the UpdatePanel asp:TextBox from code behind ?

The code behind :

  protected void Page_Load(object sender, EventArgs e)
    {
        int numberOfItems = AccountsBank.Bank_DAL.GetNumberOfActiveAccount();

        // create 'numberOfItems' asp:TextBox 
    }

Please note that I'm not looking for a TextArea , what I need are multiple asp:TextBox's .

Your help is much appreciated


Solution

  • The problem with creating the controls programatic is that you need to make sure that you create them every postback. With that said the easier and more solid way would be to use a repeater. Then you can repeat the number of textboxes depending on the number of accounts. Like this:

    Markup:

    <asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
         <ContentTemplate>
                <asp:Repeater ID="myRep" runat="server">
                   <ItemTemplate>
                        <asp:TextBox runat="server" ID="MyBox"  />
                  </ItemTemplate>
              </asp:Repeater>
         </ContentTemplate>
    </asp:UpdatePanel>
    

    Code bebind:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
           int numberOfItems = AccountsBank.Bank_DAL.GetNumberOfActiveAccount();
           myRep.DataSource = Enumerable.Range(0, numberOfItems).ToList();
           myRep.DataBind();
        }
    }
    

    Reference: