Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of DDL in C# programatically

I would like to know the way to make a list of drop down lists in C# class. I have been trying 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 like this:

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

But it breaks on line:

_ddlCollection.Add(new DropDownList());

Can you tell me how to add a few DDL's to a List?

like image 589
Antun Tun Avatar asked Oct 05 '22 07:10

Antun Tun


1 Answers

It "breaks" because you haven't initialized the local variable _ddlCollection here:

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

A local variable introduced by a local-variable-declaration is not automatically initialized and thus has no default value. Such a local variable is considered initially unassigned. A local-variable-declaration can include a local-variable-initializer, in which case the variable is considered definitely assigned in its entire scope, except within the expression provided in the local-variable-initializer..

Local variables

This is a correct initialization:

List<DropDownList> _ddlCollection = new List<DropDownList>();
like image 109
Tim Schmelter Avatar answered Oct 13 '22 09:10

Tim Schmelter