How to populate a DropDownList using List <ListItem>
I have a DropDownList.
I need to populate it with an element assembled in a List<ListItem> .
In my script, the collector was correctly populated.
But I can not fill in a DropDownList. I get an error message:
DataBinding: 'System.Web.UI.WebControls.ListItem' does not contain a property with the name 'UserName'."} <asp:DropDownList ID="uxListUsers" runat="server" DataTextField="UserName" DataValueField="UserId"> List<ListItem> myListUsersInRoles = new List<ListItem>(); foreach (aspnet_Users myUser in context.aspnet_Users) { // Use of navigation Property EntitySet if (myUser.aspnet_Roles.Any(r => r.RoleName == "CMS-AUTHOR" || r.RoleName == "CMS-EDITOR")) myListUsersInRoles.Add(new ListItem(myUser.UserName.ToString(), myUser.UserId.ToString())); } uxListUsers.DataSource = myListUsersInRoles; // MAYBE PROBLEM HERE???? uxListUsers.DataBind(); Any ideas? Thanks
When you start the listItem object, you actually run the properties (text, value)
EX ( new ListItem(myUser.User (Text PROPERTY), myUser.UserId.ToString() (Value PROPERTY) ) try linking this with
<asp:DropDownList ID="uxListUsers" runat="server" DataTextField="Text" DataValueField="Value"> the drop-down menu will accept the text properties and values ββthat are stored in the ListItem Object
and show it in the user interface
It looks like you are binding to a list of ListItem objects that do not display the UserName or UserId property. Just clear these properties (DataTextField and DataValueField) and you should be good to go.
Or even better, just add the list items you created to the dropdown directly and skip the binding.
its so simple to use ListItemCollection instead of the general List List here
change your first line
<asp:DropDownList ID="uxListUsers" runat="server"> ListItemCollection myListUsersInRoles = new ListItemCollection(); foreach (aspnet_Users myUser in context.aspnet_Users) { // Use of navigation Property EntitySet if (myUser.aspnet_Roles.Any(r => r.RoleName == "CMS-AUTHOR" || r.RoleName == "CMS-EDITOR")) myListUsersInRoles.Add(new ListItem(myUser.UserName.ToString(), myUser.UserId.ToString())); } uxListUsers.DataSource = myListUsersInRoles; // MAYBE PROBLEM HERE???? uxListUsers.DataBind(); Do not bind ListItems to a list, just add them. Binding is a way to use ListControl built-in functions to convert objects to ListItems . Since you've already done the conversion, save yourself and the server, and use Clear and Items.AddRange instead of DataSource and DataBind :
uxListUsers.Clear(); uxListUsers.Items.AddRange(myListUsersInRoles;) You also need to remove the binding directives from aspx:
<asp:DropDownList ID="uxListUsers" runat="server" />