0

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

JAN
  • 21,236
  • 66
  • 181
  • 318
  • Perhaps use a placeholder and add your created textboxes dynamically to this placeholder. Also, check this http://stackoverflow.com/questions/14816760/how-to-dynamically-create-textboxes-using-asp-net-and-then-save-their-values-in – Ivan Sivak Jan 15 '15 at 07:51

2 Answers2

3

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:

Arion
  • 31,011
  • 10
  • 70
  • 88
1

In order to programmatically add a control to a page, there must be a container for the new control. For example, if you are creating table rows, the container is the table. If there is no obvious control to act as container, you can use a PlaceHolder or Panel Web server control.

<asp:PlaceHolder ID="container" runat="server" />

This container is given a name, 'container', which you can call in code behind.

foreach(DataRow dataRow in dataTable.Rows)
{
   TextBox tb = new TextBox();
   tb.Name = "tb_" + dataRow.Id;
   tb.Text = dataRow.Content;
   container.Controls.Add(tb);
}
Allmighty
  • 1,499
  • 12
  • 19