[ACCEPTED]-C# - Dumping a list to a dropdownlist-drop-down-menu

Accepted answer
Score: 43

Why not just bind the DDL directly to the 1 List like

DropDownList ddl = new DropDownList();
ddl.DataSource = nameList;
ddl.DataBind();
Score: 23

Replace this:

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

with this:

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

Done like dinner.

0

Score: 2
ddl.DataSource = nameList; 
ddl.DataBind(); 

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

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

Score: 1

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

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

Will fix that.

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

Is your problem.

it should look more like

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

But 2 I actually like Marcus' suggestion a little 1 better.

Score: 0

You get that error because the collection 3 nameList is a List so you must access it using an index 2 not a string (you use name).

So you can write:

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

BTW 1 the best way to do this is:

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

More Related questions