views:

4853

answers:

5
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.this[int]' has some invalid arguments

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

+11  A: 

Why not just bind the DDL directly to the List like

DropDownList ddl = new DropDownList();
ddl.DataSource = nameList;
ddl.DataBind();
Marcus King
Giving it a try now.
scrot
+5  A: 

Replace this:

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

with this:

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

Done like dinner.

Mike Burton
Will try that in a minute, thank you.
scrot
A: 
    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 I actually like Marcus' suggestion a little better.

Nicholas Mancuso
A: 

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.

SoloBold
A: 

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

So you can write:

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

BTw the best way to do this is:

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

HTH

ema