C# - Dumping a list to a dropdownlist

前端 未结 6 1601
耶瑟儿~
耶瑟儿~ 2020-12-15 22:09
List nameList = new List();
DropDownList ddl = new DropDownList();

List is populated here, then sorted:



        
相关标签:
6条回答
  • 2020-12-15 22:26

    Replace this:

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

    with this:

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

    Done like dinner.

    0 讨论(0)
  • 2020-12-15 22:42

    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.

    0 讨论(0)
  • 2020-12-15 22:42
        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.

    0 讨论(0)
  • 2020-12-15 22:42

    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();
    
    0 讨论(0)
  • 2020-12-15 22:47

    Why not just bind the DDL directly to the List like

    DropDownList ddl = new DropDownList();
    ddl.DataSource = nameList;
    ddl.DataBind();
    
    0 讨论(0)
  • 2020-12-15 22:48
    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.

    0 讨论(0)
提交回复
热议问题