How to make a DDL list in C # programmatic

I would like to know how to make a list of dropdowns in a C # class. I tried like this:

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

Then I add _ddlCollection to the Asp.NET site as follows:

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

But it breaks in the line:

_ddlCollection.Add(new DropDownList());

Can you tell me how to add some DDL to the list?

+5
source share
2 answers

It breaks because you did not initialize the local variable _ddlCollectionhere:

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

, , , , . . , , , .

:

List<DropDownList> _ddlCollection = new List<DropDownList>();
+3

, _ddlCollection, , .Add .

_ddlCollection List<DropDownList>.

 _ddlCollection = new List<DropDownList>();
+1

All Articles