开发者

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?


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
       {

       }
   }
}


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


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);
            }
    }


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

   this.Controls.Add( t );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜