5

我想知道在 C# 类中制作下拉列表的方法。我一直在尝试这样:

List<DropDownList> _ddlCollection;
for (int i = 0; i < 5; i++)
            {
                _ddlCollection.Add(new DropDownList());
            }

然后我将 _ddlCollection 添加到 Asp.NET 站点,如下所示:

 foreach (DropDownList ddl in _ddlCollection)
    {
        this.Controls.Add(ddl);
    } 

但它在线中断:

_ddlCollection.Add(new DropDownList());

你能告诉我如何将一些 DDL 添加到列表中吗?

4

2 回答 2

3

它“中断”是因为您尚未在_ddlCollection此处初始化局部变量:

List<DropDownList> _ddlCollection;
// you cannot use _ddlCollection until it's initialized, 
// it would compile if you'd "initialize" it with null, 
// but then it would fail on runtime

由 local-variable-declaration 引入的局部变量不会自动初始化,因此没有默认值。这样的局部变量最初被认为是未分配的。local-variable-declaration 可以包含 local-variable-initializer,在这种情况下,除了 local-variable-initializer..

局部变量

这是一个正确的初始化:

List<DropDownList> _ddlCollection = new List<DropDownList>();
于 2013-04-25T07:51:41.293 回答
1

看起来你还没有初始化_ddlCollection,因此当你.Add中断时。

您需要_ddlCollection分配List<DropDownList>.

 _ddlCollection = new List<DropDownList>();
于 2013-04-25T07:50:40.423 回答