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

By
Advertisement

 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:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class DynamicControls : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int noofcontrols = Convert.ToInt32(txtNumbers.Text);
        for (int i = 1; i <= noofcontrols; i++)
        {
            TextBox NewTextBox = 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:


Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class DynamicControls
    Inherits System.Web.UI.Page
    Protected Sub btnSubmit_Click(sender As Object, e As EventArgs)
        Dim noofcontrols As Integer = Convert.ToInt32(txtNumbers.Text)
        For i As Integer = 1 To noofcontrols
            Dim NewTextBox As 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)
        Next
    End Sub
End Class



Output:


No of Text boxes

0 comments:

Post a Comment

Online Casino