Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a DropDownList using a List<ListItem>

Tags:

c#

asp.net

I have a DropDownList.

I need populate it with item collected in a List<ListItem>.

In my script, collector has been populated properly.

But I cannot populate the DropDownList. I receive an error:

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

like image 367
GibboK Avatar asked Dec 13 '22 16:12

GibboK


1 Answers

When you init the listItem Object you actually init the properties (text,value)

EX ( new ListItem(myUser.User (Text PROPERTY), myUser.UserId.ToString() (Value PROPERTY) )

try to bind that with

    <asp:DropDownList ID="uxListUsers" runat="server" DataTextField="Text" 
DataValueField="Value">    

the dropdown will take the Text and Value Properties which store in the ListItem Object

and show it in the user interface

like image 161
GavrielSl Avatar answered Dec 28 '22 02:12

GavrielSl