Wednesday, December 26, 2012

Creating Update Panel in Code Behind Dynamically

Creating Update Panel in Code Behind Dynamically

Creating Update Panel in code behind dynamically can be a bit tricky, comparing to doing it at the front end. Here's a quick view of the code we write to do this.
UpdatePanel up = new UpdatePanel();
up.ID = "UpdatePanel1";
up.ChildrenAsTriggers = true;
up.UpdateMode = UpdatePanelUpdateMode.Conditional;
this.Controls.Add(up);
this.textBox = new TextBox();
this.textBox.ID = "TextBox";
up.ContentTemplateContainer.Controls.Add(this.textBox);
this.label = new Label();
this.label.Text = "Enter your name.";
up.ContentTemplateContainer.Controls.Add(this.label);
Button button = new Button();
button.Text = "Say Hello";
button.Click += new EventHandler(HandleButtonClick);
up.ContentTemplateContainer.Controls.Add(button);
and a testing event handler:
private void HandleButtonClick(object sender, EventArgs eventArgs)
        {
            this.label.Text = "Hello " + this.textBox.Text;
        }