C# – Dumping a list to a dropdownlist


List<String> nameList = new List<String>();
DropDownList ddl = new DropDownList();

List is populated here, then sorted:


Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):

foreach (string name in nameList){
    ddl.Items.Add(new ListItem(nameList[name].ToString()));

No workie – any suggestions? It's giving me compile errors:

Error - The best overloaded method match for 'System.Collections.Generic.List<string>.this[int]' has some invalid arguments 

Error - Argument '1': cannot convert from 'string' to 'int'

Best Answer

Why not just bind the DDL directly to the List like

DropDownList ddl = new DropDownList();
ddl.DataSource = nameList;