I have a problem that I can't solve when I load controls dynamically. I have 3 states on a page that I traverse through and I load as many buttons on the page as the page state number + 1. For example, on state 0, I load 1 button, state 2 - 2 buttons, etc.
The problem is after I move to a new page state, the button click event(s) of the dynamic buttons will not be wired up and won't fire until the second click of each button.
CSharp Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebTest
{
public partial class DynamicButtonTest : System.Web.UI.Page
{
private int _PageState {
get {
if(ViewState["PageState"] != null) {
return (int)ViewState["PageState"];
}
return 0; // default
}
set {
ViewState["PageState"] = value;
}
}
private void LoadButtons(int pageState) {
panelButtons.Controls.Clear();
for(int i = 0; i < pageState + 1; i++) {
Button b = new Button();
b.Text = i.ToString();
b.Click += new EventHandler(b_Click);
panelButtons.Controls.Add(b);
}
_PageState = pageState;
}
void b_Click(object sender, EventArgs e) {
Button b = (Button)sender;
Response.Write("Button " + b.Text + " was clicked.");
}
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
LoadButtons(0);
}
else {
LoadButtons(_PageState);
}
}
protected void btnBack_Click(object sender, EventArgs e) {
switch(_PageState) {
case 0:
// Initial State - do nothing
break;
case 1:
// move to PageState 0
LoadButtons(0);
break;
case 2:
// move to PageState 1
LoadButtons(1);
break;
default:
break;
}
}
protected void btnNext_Click(object sender, EventArgs e) {
switch(_PageState) {
case 0:
// move to PageState 2
LoadButtons(1);
break;
case 1:
// move to PageState 3
LoadButtons(2);
break;
case 2:
// Last State - do nothing
break;
default:
break;
}
}
}
}
PHP Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicButtonTest.aspx.cs" Inherits="WebTest.DynamicButtonTest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnBack" runat="server" Text="Back" onclick="btnBack_Click" /><asp:Button ID="btnNext" runat="server" Text="Next" onclick="btnNext_Click" />
<asp:Panel ID="panelButtons" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>