I think what's really getting you is the if(isPostBack). It seems weird, that you'd want to recreate your dynamic controls on postback, but since a web page is stateless, it doesn't know what your control is anymore. I did a little exercise myself to prove it. Put a breakpoint on the aList_SelectedIndexChanged event and it will visit it on postback with the right value.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<asp:Panel ID="pnlMain" runat="server" Style="width: 100%;">
</asp:Panel>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
CreateDropDown();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void CreateDropDown()
{
DropDownList aList = new DropDownList();
for (int i = 0; i < 5; i++)
{
aList.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
aList.SelectedIndexChanged += new EventHandler(aList_SelectedIndexChanged);
aList.AutoPostBack = true;
pnlMain.Controls.Add(aList);
}
private void aList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList aList = (DropDownList)sender;
int i = -1;
if (Int32.TryParse(aList.SelectedValue, out i))
{
}
}
}