【发布时间】:2012-06-11 21:20:44
【问题描述】:
我有一个包含 27 个 DropDownLists 供用户输入的表格。我的表格中有 27 次出现此 HTML:
<span id="s1" runat="server"><asp:PlaceHolder ID="p1" runat="server"></asp:PlaceHolder></span>
span 的索引为 s1, s2, ..., s27,PlaceHolders 的索引为 p1, p2, ..., p27。对跨度进行索引的原因是,我可以用所做的任何选择替换 DropDownList —— 即,DropDownList 将消失。
这是我生成 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);
}
}
最后一行出现运行时错误。我可以选择我想要的任何 DropDownList 并进行选择,但是当我选择第二个 DropDownList 并进行选择时,我收到此错误:
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: }
当我用蛮力做这件事时,这似乎奏效了:
p1.Controls.Add(DropList1);
p2.Controls.Add(DropList2);
etc....
但现在我遇到了一个错误。我已经在调试器中运行了它,但我找不到空引用。
感谢任何建议。
问候。
【问题讨论】: