我正在动态创建复选框并想要显示现有选择或想要动态检查它们。这是创建复选框的代码

    private void Role()
    {
        SystemUserDal dal = new SystemUserDal();
        var roles = dal.GetRolesList();
        foreach (KeyValuePair<Guid, string> r in roles)
        {

            CheckBox chk = new CheckBox();
            chk.ID = r.Value;
            chk.Text = r.Value;
            rolepanel.Controls.Add(chk);
        }
    }

我有

      protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SystemUserDal dal = new SystemUserDal();
            var userID = Guid.Parse(Request.QueryString["ID"].ToString());
            var user = dal.getSystemUserByID(userID);
            if (user != null)
            {
                Role();
                var role = user.Roles;


                textuserid.Text = user.UserId.ToString();

user.Roles具有分配特定用户的所有角色。 如何标记动态创建的复选框?

我尝试过此方法,但仍能完成工作,因为角色具有多个价值

    private void Role(string role)
    {
        SystemUserDal dal = new SystemUserDal();
        var userId = Guid.Parse(Request.QueryString["ID"].ToString());
        var roles = dal.GetRolesList(userId);
        foreach (KeyValuePair<Guid, string> r in roles)
        {

            CheckBox chk = new CheckBox();
            chk.ID = r.Value;
            chk.Text = r.Value;
            if (role == r.Value)
            {
                chk.Checked = true;

            } rolepanel.Controls.Add(chk);
        }
    }

===============>>#1 票数:0 已采纳

可能重写您的Roles()函数

foreach (KeyValuePair<Guid, string> r in roles)
{

    CheckBox chk = new CheckBox();
    chk.ID = r.Value;
    chk.Text = r.Value;

    if(User.IsInRole(r.Value))
       chk.Checked = true;

    rolepanel.Controls.Add(chk);
}

更好的选择是使用<asp:CheckBoxList />控件

<asp:CheckBoxList ID="RolesList" runat="server">
</asp:CheckBoxList>

后台代码

for (int i = 0; i < RolesList.Items.Count; i++)
{
    if (User.IsInRole(RolesList.Items[i].Value))
       RolesList.Items[i].Selected = true;
}

  ask by user2167089 translate from so

未解决问题?本站智能推荐: