I have a table that includes 27 DropDownLists for user input. My table has 27 occurrences of this HTML:
<span id="s1" runat="server"><asp:PlaceHolder ID="p1" runat="server"></asp:PlaceHolder></span>
where the spans are indexed s1, s2, ..., s27 and the PlaceHolders are indexed p1, p2, ..., p27. The reason that the spans are indexed is so that I can replace the DropDownList with whatever selection was made -- ie, the DropDownList will disappear.
Here is how I am generating the DropDownLists:
protected void Page_Load(object sender, EventArgs e)
{
var data = CreateDataSource();
int x;
for (x = 1; x <= 27; x++)
{
DropDownList dl = new DropDownList();
string index = x.ToString();
dl.ID = "TrendList" + index;
dl.AutoPostBack = true;
dl.SelectedIndexChanged += new EventHandler(this.Selection_Change);
dl.DataSource = data;
dl.DataTextField = "TrendTextField";
dl.DataValueField = "TrendValueField";
dl.DataBind();
if (!IsPostBack)
{
dl.SelectedIndex = 0;
}
PlaceHolder ph = (PlaceHolder)form1.FindControl("p" + index);
ph.Controls.Add(dl);
}
}
A runtime error occurs at the last line. I can select any DropDownList I want and make a selection, but when I select a second DropDownList and make a selection I get this error:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Line 46: }
Line 47: PlaceHolder ph = (PlaceHolder)form1.FindControl("p" + index);
Line 48: ph.Controls.Add(dl);
Line 49: }
This seemed to be working when I was doing it by brute force:
p1.Controls.Add(DropList1);
p2.Controls.Add(DropList2);
etc....
but now I am getting an error. I have run this in the debugger but I can't find a null reference.
Any advice is appreciated.
Regards.