How to dynamically create textbox through code behind, and manipulate the fields created later

Viewed 24

I'm trying here and I'm not succeeding, so I decided to post here to see if anyone can help me. Thanks in advance...

I have structure below in a table, I need that when creating the new textbox they keep in the same structure of the table.

I can't do it via javascript, I need to do it by C# itself...

<body>
    <form id="form1" runat="server">
        <table runat="server" id="tbform">
            <tr>
                <td><asp:TextBox runat="server" ID="txt01"></asp:TextBox></td>
                <td><asp:TextBox runat="server" ID="txt02"></asp:TextBox></td>
                <td><asp:TextBox runat="server" ID="txt03"></asp:TextBox></td>
                <td><asp:TextBox runat="server" ID="txt04"></asp:TextBox></td>
                <td><asp:Button runat="server" ID="btnCreate" Text="Create" OnClick="btnCreate_Click" /></td>
            </tr>
        </table>
    </form>
</body>

1 Answers

For this I recommend use GridView and button for add new row:

page

<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
    <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>

code behind

protected void ButtonAdd_Click(object sender, EventArgs e)
{
      AddNewRowToGrid()
}

private void AddNewRowToGrid()
{
    int rowIndex = 0;

    if (ViewState["CurrentTable"] != null)
    {
        DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        DataRow drCurrentRow = null;
        if (dtCurrentTable.Rows.Count > 0)
        {
            for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
            {
                //extract the TextBox values
            }
            dtCurrentTable.Rows.Add(drCurrentRow);
            ViewState["CurrentTable"] = dtCurrentTable;

            Gridview1.DataSource = dtCurrentTable;
            Gridview1.DataBind();
        }
    }
    else
    {
        Response.Write("ViewState is null");
    }

    //Set Previous Data on Postbacks
    SetPreviousData();
}
Related