C#.Net – Dynamically create textbox in asp.net

 Aspx Code:

<!DOCTYPE html>
<html>
<head runat=”server”>
    <title>Dynamically create textboxes in ASP.Net</title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <table>
            <tr>
                <td>
                    No of Text boxes
                </td>
                <td>
                    <asp:TextBox ID=”txtNumbers” runat=”server”></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Button ID=”btnSubmit” runat=”server” OnClick=”btnSubmit_Click” Text=”Submit” />
                </td>
        </table>
        <br />
      
    </div>
    </form>
</body>
</html>
 C#.Net Code:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
public partial class DynamicControls : System.Web.UI.Page
{
    protected void btnSubmit_Click(objectsender, EventArgs e)
    {
        intnoofcontrols = Convert.ToInt32(txtNumbers.Text);
        for (int i = 1; i <= noofcontrols; i++)
        {
            TextBoxNewTextBox = new TextBox();
            NewTextBox.ID = “TextBox” + i.ToString();
            NewTextBox.Style[“Clear”] = “Both”;
            NewTextBox.Style[“Float”] = “Left”;
            NewTextBox.Style[“Top”] = “25px”;
            NewTextBox.Style[“Left”] = “100px”;
            //form1 is a form in my .aspx file with runat=server attribute
            form1.Controls.Add(NewTextBox);
        }
    }
}

Equivalent VB.Net Code:

ImportsSystem.Collections.Generic
ImportsSystem.Linq
ImportsSystem.Web
ImportsSystem.Web.UI
ImportsSystem.Web.UI.WebControls
Partial Public Class DynamicControls
    InheritsSystem.Web.UI.Page
    Protected Sub btnSubmit_Click(sender AsObject, e As EventArgs)
        Dimnoofcontrols As Integer= Convert.ToInt32(txtNumbers.Text)
        For i As Integer = 1 To noofcontrols
            DimNewTextBox As NewTextBox()
            NewTextBox.ID = “TextBox” & i.ToString()
            NewTextBox.Style(“Clear”) = “Both”
            NewTextBox.Style(“Float”) = “Left”
            NewTextBox.Style(“Top”) = “25px”
            NewTextBox.Style(“Left”) = “100px”
            ‘form1 is a form in my .aspx file with runat=server attribute
            form1.Controls.Add(NewTextBox)
        Next
    End Sub
End Class

Output:

No of Text boxes


Leave a Reply

Your email address will not be published. Required fields are marked *