Another question from an event - this time today's MSDN event at the Microsoft London offices. Can I create and add UpdatePanels to my page dynamically? Mais ouis! The code below shows a simple example. Create an UpdatePanel instance then create your "child" controls and add them to the Controls collection of the ContentTemplateContainer property of the UpdatePanel. Finally add the UpdatePanel to the Form and you're done. You'll need a <ScriptManager> on your page of course.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC 
  "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

  private Label randomLabel;

  protected override void  OnLoad(EventArgs e)
  {
    UpdatePanel u1 = new UpdatePanel();

    randomLabel = new Label();
    randomLabel.Text = "Value Not Set Yet ";

    Button b = new Button();
    b.Text = "Submit";
    b.Click += new EventHandler(OnClick);

    u1.ContentTemplateContainer.Controls.Add(randomLabel);
    u1.ContentTemplateContainer.Controls.Add(b);

    Page.Form.Controls.Add(u1);
  }

  protected void OnClick(Object sender, EventArgs e)
  {
    randomLabel.Text = new Random().Next(1, 110).ToString() + " ";
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
  <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <div></div>
  </form>
</body>
</html>
Technorati tags: , ,