Thursday, January 19, 2012

Dynamic Controls



1 - Página ASP.NET Web 


<form runat="server">
    Criar quantas TextBoxes?
    <asp:textbox runat="Server" id="txtTBCount" Columns="3" />


    <asp:RangeValidator runat="server" ControlToValidate="txtTBCount"
           MinimumValue="1" MaximumValue="10" Type="Integer"
           ErrorMessage="Escolha um número entre 1 e 10" />


    <br />
    <asp:button runat="server" Text="Criar TextBoxes"
           OnClick="CreateTextBoxes" />


    <p>
    <asp:PlaceHolder runat="server" id="TextBoxesHere" />
</form>




2 - Esta function ASP.NET  CreateTextBoxes irá criar na tela



void CreateTextBoxes(Object sender, EventArgs e)

  int n = Int32.Parse(txtTBCount.Text);
      
  // now, create n TextBoxes, adding them to the PlaceHolder TextBoxesHere
  for (int i = 0; i < n; i++)
  {
    TextBoxesHere.Controls.Add(new TextBox());
  }
      
  // now, set the Text property of each TextBox
  IterateThroughChildren(this);
}


3 - Confirma que o controle criado é um TextBox



void IterateThroughChildren(Control parent)
{
  foreach (Control c in parent.Controls)
  {
    if (c.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")
          && c.ID == null)
    {
      // ...do something...
    }
        
    if (c.Controls.Count > 0)
    {          
      IterateThroughChildren(c);          
    }
  }
}

No comments: