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?
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With