user6067265
user6067265

Reputation:

C# ASP.NET checkboxlist on page load check items from database

I am working with checkboxlist in asp.net and what I WANT TO do is next: for selected user get his roles from database ( lets say roles are previously selected and stored to database and that is ok!) and now I just want to fill that checkboxlist with selected roles (in previous step) from database..

But unfortunately I can not do that on the way I imagined it might work, here is my code:

if (!IsPostBack)
{
    int playerID = Convert.ToInt32(Request.QueryString["player"]);
    var player = DAPlayers.GetByIgracId(playerID);

    if (player != null)
    {
        checkboxRoles.DataSource=DAPlayers.GetAllRoles();
        checkboxRoles.DataTextField = "Name";


        player.Roles =DAPlayers.GetAllRolesByPlayer(player.playerID);

        for (int i = 0; i < checkboxRoles.Items.Count; i++)
        {
            if(player.Roles.Contains(checkboxRoles.Items[i])) //HERE I GOT THE ERROR 
                checkboxRoles.Items[i].Selected = true;
        }
    }
}

ERROR NUMBER 1:

cannot convert from 'System.Web.UI.WebControls.ListItem' to 'MYPROJECT.Data.Roles'

ERROR NUMBER 2:

The best overloaded method match for 'System.Collections.Generic.List.Contains(MYPROJECT.Data.Roles)' has some invalid arguments

My Role class

`public partial class Roles { public Roles() { this.UserRoles = new HashSet(); }

    public int RoleID { get; set; }
    public string Name { get; set; }
    public string Desc { get; set; }

    public virtual ICollection<UserRoles> UserRoles { get; set; }
}`

Thanks guys,

Cheers!

Upvotes: 0

Views: 2053

Answers (1)

Rahul
Rahul

Reputation: 77926

You need to call the Text property like checkboxRoles.Items[i].Text and again while comparing you will have to compare it with a string property of Role object which can't say for sure unless you post the code for Roles class

Per your comment: In that case get the Names list and compare with that like

var roleNames = igrac.Roles.Select(r => r.Name);

 if(roleNames.Contains(checkboxRoles.Items[i].Text)) 
   checkboxRoles.Items[i].Selected = true;

Upvotes: 1

Related Questions