Reputation: 47
I am creating a web form in asp.net and C#.
The form asks the user how many children the user has, and then after clicking on the Proceed button, the application should prompt for each child's name.
I know using a Console Application, the coding will be:
for (int i = 0 ; i < noOfChildren ; i++)
{
Console.Write("Child's Name: ");
name = Console.ReadLine();
}
How will I code asp.net/C# application to do the same thing, but only displaying the Labels and textboxes the same amount of times the user has entered...?
Thanks in advance!
Upvotes: 1
Views: 234
Reputation: 647
In below example it creates only Textbox
dynamically but you can add your style and label control dynamic based your requirements.
In Aspx
page, create form
tag in html 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>
and in your code behind c# file,
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);
}
}
I assume this is what you want.
Upvotes: 1