C# - Dumping a list to a dropdownlist

77,590

Solution 1

Replace this:

 ddl.Items.Add(new ListItem(nameList[name].ToString()));

with this:

 ddl.Items.Add(new ListItem(name));

Done like dinner.

Solution 2

Why not just bind the DDL directly to the List like

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

Solution 3

ddl.DataSource = nameList; 
ddl.DataBind(); 

Doesn't work if it's a SharePoint list - Error: Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource. Decided to chime in, in case any SharePoint developers thought this was for an SPList instead of List<string>, as was written above.

There is a way to bind to an SPList, but you'd use an SPListItemCollection, or go one better and use an SPDataSource. For the SharePoint developers, see this blog by Chris O' Brien.

Solution 4

That would be because List is not indexed by string (name) but by ints.

foreach (string name in nameList)
{
    ddl.Items.Add(new ListItem(name));
}

Will fix that.

Share:
77,590
scrot
Author by

scrot

Updated on December 17, 2020

Comments

  • scrot
    scrot over 3 years
    List<String> nameList = new List<String>();
    DropDownList ddl = new DropDownList();
    

    List is populated here, then sorted:

    nameList.Sort();
    

    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'