How do I create a table with my dynamically created textboxes?

2.1k Views Asked by At

In this project I am using a users input to create textboxes dynamically:

        int ReqPO = Convert.ToInt32(txtReqPONum.Text);
        int n = ReqPO;
        for (int i = 0; i < n; i++)
        {
            TextBox MyTextBox = new TextBox();
            //Assigning the textbox ID name 
            MyTextBox.ID = "txtPOAmount" + "" + ViewState["num"] + i;
            this.Form.Controls.Add(MyTextBox);
        }

Edited Here is where I got which is not too far. Now Im just getting tons of errors

Table table1 = new Table();
        TableRow tr = null;
        TableCell tc = null;

        int ReqPO = Convert.ToInt32(txtReqPONum.Text);
        int n = ReqPO;

        for (int a = 0; a < n; a++) 
        {
           tr = new TableRow();

                for (int b = 0; b < n; b++)
                {
                    TextBox MyTextBox = new TextBox();

                    for (int c = 0; c < 3; c++)
                    {

                        tc = new TableCell();
                        table1.Rows.Add(tc);
                    }

                    //Assigning the textbox ID name 
                    MyTextBox.ID = "txtPOAmount" + "" + ViewState["num"] + b;
                    this.Form.Controls.Add(MyTextBox);
                }

                table1.Rows.Add(tr);
        }

        this.Form.Controls.Add(table1);

The problem is that I am using it in a wizard and I want to display the new textbox fields that appear in a table in their own rows. Currently they are displaying side by side below the asp:wizard previous and next buttons.

1

There are 1 best solutions below

1
Dmitry Kirsanov On

If you want to display dynamic textboxes in a table, then just create the HTML table dynamically. Create TR (rows), then TD (cells), then create the textbox, add it to cell, then add cell to row, row to table and table to whatever control you want to place it in.

If you are creating the HTML table in your web page, then just adding the runat="server" and giving it an ID will make it visible at the server side and you'll be able to manipulate it just like any other control.

In other words, don't add controls to the Form, add it to particular parent control.

<asp:Wizard runat="server">
    <WizardSteps>
        <asp:WizardStep>
            <table runat="server" id="tblTextBoxes">

            </table>
        </asp:WizardStep>
    </WizardSteps>
</asp:Wizard>

tblTextBoxes.Controls.Add(new TextBox() {ID = "txtNewTextBox", Text = "Text of new control"});

(the code above is for example only, you can't add TextBox directly to the table, but you can to TD within TR tag).