【问题标题】:Creating Multiple DropDownLists创建多个下拉列表
【发布时间】: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....

但现在我遇到了一个错误。我已经在调试器中运行了它,但我找不到空引用。

感谢任何建议。

问候。

【问题讨论】:

    标签: c# asp.net forms


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      FindControl 方法不是递归的,因此您必须使用一种方法来遍历嵌套对象。这是在 SO 上找到的一个很好的例子:C#, FindControl

      【讨论】:

      • 感谢您的链接。我尝试递归搜索,但仍然得到相同的空指针异常。
      【解决方案3】:

      从技术上讲,占位符不在 form1 中,它们位于 form1 中的跨度中(或者跨度在其他一些控件中,等等)。

      这适用于跨度嵌套在 form1 中的情况:

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

      【讨论】:

      • 谢谢。我试过这个,我得到了同样的空指针异常。
      • @Kevin - 如果你想发布整个标记(无论如何都是 form1),我会看看我是否能想出正确的代码。
      【解决方案4】:

      问题原来是在每个新页面上都调用了这个函数。这意味着在第一次运行后第一个占位符不再存在并引发空引用错误。用这段代码解决了这个问题:

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

      【讨论】:

        猜你喜欢
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多