user904406
user904406

Reputation: 57

asp.net auto generated textboxes ID on webform

I am using C# on Visual Studio. I want to generate a webform with auto numbered Textboxes depending on the input from the previous page. What is the best way to do this loop?

For example:

Input is 4

The next page should generate textboxes with ID of

Something like this :

<asp:TextBox ID="name1" runat="server"></asp:TextBox>
<asp:TextBox ID="name2" runat="server"></asp:TextBox>
<asp:TextBox ID="name3" runat="server"></asp:TextBox>
<asp:TextBox ID="name4" runat="server"></asp:TextBox>

Part 2 of my question is that if I want to call them when a Button is click, how should I use a loop the get those ID?

Upvotes: 1

Views: 5174

Answers (4)

sharmila
sharmila

Reputation: 1533

Check this code. In first page...

protected void Button1_Click(object sender, EventArgs e)
  {          
    Response.Redirect("Default.aspx?Name=" + TextBox1.Text);
  }

In second page you can get the value from querystring and create controls dynamically

protected void Page_Load(object sender, EventArgs e)
   {
      if (Request.QueryString["Name"] != null)
          Response.Write(Request.QueryString["Name"]);

            Int32 howmany = Int32.Parse(Request.QueryString["Name"]);

            for (int i = 1; i < howmany + 1; i++)
            {
                TextBox tb = new TextBox();
                tb.ID = "name" + i;
                form1.Controls.Add(tb);
            }
    }

Upvotes: 1

V4Vendetta
V4Vendetta

Reputation: 38210

You could create those controls in the Page Init event handler by say loop for the number of times the control needs to made available.

Please remember since these are dynamic controls they need to be recreated during postbacks and will not be done automatically.

Further Dynamic controls and postback

Upvotes: 1

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

for ( int i=0; i<4; i++ )
{
   TextBox t = new TextBox();
   t.ID = "name" + i.ToString();

   this.Controls.Add( t );
}

Upvotes: 0

Arief
Arief

Reputation: 6085

Use for loop and PlaceHolder control to create dynamic TextBox controls

<asp:PlaceHolder ID="phDynamicTextBox" runat="server" />

int inputFromPreviousPost = 4;
for(int i = 1; i <= inputFromPreviousPost; i++)
{
    TextBox t = new TextBox();
    t.ID = "name" + i.ToString();
}

//on button click retrieve controls inside placeholder control
protected void Button_Click(object sender, EventArgs e)
{
   foreach(Control c in phDynamicTextBox.Controls)
   {
       try
       {
           TextBox t = (TextBox)c;

           // gets textbox ID property
           Response.Write(t.ID);
       }
       catch
       {

       }
   }
}

Upvotes: 2

Related Questions