2012-06-11 64 views
0

我有一个包含27个DropDownLists用户输入的表。我的表有27次出现这样的HTML:创建多个DropDownLists

<span id="s1" runat="server"><asp:PlaceHolder ID="p1" runat="server"></asp:PlaceHolder></span> 

其中跨度被索引S1,S2,...,S27和占位符索引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.... 

但现在我得到一个错误。我在调试器中运行了这个,但是我找不到空引用。

任何意见表示赞赏。

问候。

回答

0

问题原来是这个函数在每个新页面上调用。这意味着第一次运行后第一个占位符不再存在,并抛出空引用错误。该问题已通过此代码解决:

if (placeHolder != null) 
{ 
    placeHolder.Controls.Add(ddl); 
} 
0

您是否尝试过使用一个占位符?错误消息似乎是关于如何没有由“p”+ index的ID占位符.ToString()

0

占位符在技术上不在form1中,它们位于form1中的跨度或者跨度在其他控制中等)。

这会工作在跨度嵌套在Form1的情况:

var s = form1.FindControl("s" + index); 
var ph = s.FindControl("p" + index); 
ph.Controls.Add(dl); 
+0

谢谢。我试过这个,并得到了相同的空指针异常。 – Kevin

+0

@Kevin - 如果你想发布整个标记(无论如何都是form1的),我会看一看,看看我能不能拿出正确的代码。 – hmqcnoesy

0

FindControl方法不是递归的,所以你将不得不使用一种方法,通过嵌套对象进行迭代。这里有一个很好的例子在SO上发现:C#, FindControl

+0

感谢您的链接。我试着递归搜索,但我仍然得到相同的空指针异常。 – Kevin