ユーザー入力用の 27 の DropDownLists を含むテーブルがあります。私のテーブルには、次の HTML が 27 回出現しています。
<span id="s1" runat="server"><asp:PlaceHolder ID="p1" runat="server"></asp:PlaceHolder></span>
ここで、スパンには s1、s2、...、s27 のインデックスが付けられ、PlaceHolder には 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 を選択して選択できますが、2 つ目の 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....
しかし、今はエラーが発生しています。これをデバッガーで実行しましたが、null 参照が見つかりません。
アドバイスをいただければ幸いです。
よろしく。