Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

.NET Show roles in DropDownList within GridView

Posted on 2009-07-09
2
Medium Priority
?
412 Views
Last Modified: 2013-11-26
Hi. I am new to .NET so please be obvious and detailed in your answers!
I am trying to implement both Membership and Roles in a system using SQL Server Express.
Membership so far is working OK. I'm building a web interface to manage the assignment of roles which users belong to.

I want a list of all my users in a GridView - with paging. At the moment, I have their username, email, date created, and an empty dropdownlist showing for all the users, in a paging gridview.

To build on what I currently have, I need three things:

1) Populate the dropdownlist of each row with all the roles in the system
2) Set the dropdownlist to display for each row (or "user") the role they are part of.
3) On changing the dropdownlist, postback and update the roles table accordingly.

Attached is the current code below. I appreciate this is a lot of work so will award points accordingly. I just have no idea about how to go about this.

Chris


<asp:GridView ID="EntireUserList" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="#BFCFFF" BackColor="White" Width="100%" HeaderStyle-BackColor="#809FFF" HeaderStyle-Font-Italic="False" HeaderStyle-HorizontalAlign="Center" BorderWidth="1" BorderStyle="Solid" BorderColor="Black">
        <Columns> 
                    <asp:BoundField DataField="UserName" HeaderText="Username" />
                    <asp:BoundField DataField="Email" HeaderText="Email" />
                    <asp:BoundField DataField="CreationDate" HeaderText="Date Created" />
          <asp:TemplateField HeaderText="Assigned Role">
          <ItemTemplate>
          <asp:DropDownList ID="RoleDropdown" runat="server" AutoPostBack="True"></asp:DropDownList>
          </ItemTemplate>
          </asp:TemplateField>
          </Columns> 
        </asp:GridView>

Open in new window

0
Comment
Question by:chris_smith_51
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 18

Accepted Solution

by:
carlnorrbom earned 1400 total points
ID: 24821683
Hi,

Look at the attached code to see how you can do what you want! What you need to keep in mind, your app logic will break if a user belongs to more than one group! I have added logic to clear group membership before assigning a new group in order for the app logic not to break. To summarize the key components:

1. In your markup you need to add: OnSelectedIndexChanged="RoleDropdown_SelectedIndexChanged" to the declarative code for your dropdown.

2. I have abstracted out the membership user collecting and binding of the gridview to a private sub: BindAllUsers()

3. The collecting of all available roles and adding them as items to the dropdowns is taken care of in the EntireUserList_RowDataBound event for each row. This could be optimized further by loading available roles into a session variable for instance. Also, the code will break if a user has NOT been assigned a role on the following line of code: ddlRoles.SelectedValue = Roles.GetRolesForUser(u.UserName)(0).ToString() - it will throw an IndexOutOfRange exception. You might want to add for instance a try catch block or whatever.

4. The updating of role assignment for the users are done in the RoleDropdown_SelectedIndexChanged event.

Hope this helps!

/Carl.
MembershipAdministration.aspx:
 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="MembershipAdministration.aspx.vb"
    Inherits="MembershipAdministration" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="EntireUserList" runat="server" AutoGenerateColumns="False" AlternatingRowStyle-BackColor="#BFCFFF"
            BackColor="White" Width="100%" HeaderStyle-BackColor="#809FFF" HeaderStyle-Font-Italic="False"
            HeaderStyle-HorizontalAlign="Center" BorderWidth="1" BorderStyle="Solid" BorderColor="Black">
            <Columns>
                <asp:BoundField DataField="UserName" HeaderText="Username" />
                <asp:BoundField DataField="Email" HeaderText="Email" />
                <asp:BoundField DataField="CreationDate" HeaderText="Date Created" />
                <asp:TemplateField HeaderText="Assigned Role">
                    <ItemTemplate>
                        <asp:DropDownList ID="RoleDropdown" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RoleDropdown_SelectedIndexChanged">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
 
MembershipAdministration.aspx.vb:
 
Imports System.Data
 
 
Partial Class MembershipAdministration
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        BindAllUsers(EntireUserList)
    End Sub
 
    Protected Sub EntireUserList_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles EntireUserList.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim u As MembershipUser = Membership.GetUser(e.Row.Cells(0).Text.ToString())
            Dim rolesCollection As String() = Roles.GetAllRoles()
            Dim ddlRoles As DropDownList = CType(e.Row.FindControl("RoleDropdown"), DropDownList)
            For Each role As String In rolesCollection
                ddlRoles.Items.Add(New ListItem(role.ToString(), role.ToString()))
            Next
            ddlRoles.SelectedValue = Roles.GetRolesForUser(u.UserName)(0).ToString()
        End If
    End Sub
 
    Protected Sub RoleDropdown_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim row As GridViewRow = CType(CType(CType(sender, DropDownList).Parent, DataControlFieldCell).Parent, GridViewRow)
        Dim u As MembershipUser = Membership.GetUser(row.Cells(0).Text.ToString())
        Roles.RemoveUserFromRole(u.UserName.ToString(), Roles.GetRolesForUser(u.UserName.ToString())(0)) 'this is needed to not break you app logic!
        Roles.AddUserToRole(u.UserName.ToString(), CType(sender, DropDownList).SelectedValue.ToString())
        BindAllUsers(EntireUserList)
    End Sub
 
    Private Sub BindAllUsers(ByVal gv As GridView)
        Dim users As MembershipUserCollection = Membership.GetAllUsers()
        Dim dtUsers As New DataTable()
        dtUsers.Columns.Add("UserName", GetType(System.String))
        dtUsers.Columns.Add("Email", GetType(System.String))
        dtUsers.Columns.Add("CreationDate", GetType(System.DateTime))
        Dim objUser(2) As Object
        For Each u As MembershipUser In users
            objUser(0) = u.UserName.ToString()
            objUser(1) = u.Email.ToString()
            objUser(2) = u.CreationDate
            dtUsers.Rows.Add(objUser)
        Next
        gv.DataSource = dtUsers
        gv.DataBind()
    End Sub
 
End Class

Open in new window

0
 
LVL 2

Author Closing Comment

by:chris_smith_51
ID: 31601577
perfect! thanks so much!
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

664 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question