Home > ASP.Net > Manage User Account (for Admin)

Manage User Account (for Admin)


Hi All,

Try this Example to Manage User Account using Memebership

for more details you can see this article here

1) We will create Page called “ManageUsers.aspx” which will display all users data in Gridview so the page will be like this :-


<script language="javascript" type="text/javascript">
//--- For Checkbox in Gridview
function SelectAll(id)
      {
       var frm = document.forms[0];

            for (i=0;i<frm.elements.length;i++)
            {
                if (frm.elements[i].type =="checkbox")
                {
           frm.elements[i].checked = document.getElementById(id).checked;

                }
            }

        }
</script>
    <br />
    <strong><span style="font-size: 11pt; color: #0066ff">Users Account Management</span></strong><p>
    </p>
    <b>- The total registered users is:
        <asp:Literal ID="lblTotalUsers" runat="server"></asp:Literal><br />
        <br />
        - The total online users at this moment:
        <asp:Literal ID="lblOnlineUsers" runat="server"></asp:Literal></b>
    <p>
    </p>
    In order to display all users whose name begins with letter click on the link letter:
    <p>
    </p>
    <asp:Repeater ID="rptAlphabetBar" runat="server" OnItemCommand="rptAlphabetBar_ItemCommand">
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%# Container.DataItem %>'
                Text='<%# Container.DataItem %>'></asp:LinkButton>
            
        </ItemTemplate>
    </asp:Repeater>
    <p>
    </p>
    Use the below feature to search users by partial username or e-mail:
    <p>
    </p>
    <asp: DropDownList ID="ddlUserSearchTypes" runat="server" Style="position: static">
        <asp:ListItem Selected="true" Text="UserName"></asp:ListItem>
        <asp:ListItem Text="E-mail"></asp:ListItem>
    </asp: DropDownList>
    contains
    <asp:TextBox ID="txtSearchText" runat="server" Style="position: static"></asp:TextBox>
    <asp:Button ID="btnSearch" runat="server" Font-Bold="True" OnClick="btnSearch_Click"
        Style="position: static" Text="Search" BackColor="White" BorderColor="#507CD1"
        BorderStyle="Solid" BorderWidth="1px" Font-Names="Times New Roman"
        Font-Size="10.5pt" ForeColor="#284E98"/>
    <br />
    <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="UserName" ForeColor="#333333"
        GridLines="None" OnDataBound="gvUsers_DataBound" OnRowDataBound="gvUsers_RowDataBound" Style="position: static">
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="cbxAll" runat="server" Style="position: static" />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="cbxId" runat="server" Style="position: static" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="User Name">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UserName") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblUserName" runat="server" Text='<%# Bind("UserName") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="Email" HeaderText="Email" DataFormatString="<a href=mailto:{0}>{0}</a>" HtmlEncode="False" />
            <asp:TemplateField HeaderText="Created">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("CreationDate") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("CreationDate", "{0:dd/MM/yyyy}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Last activity">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("LastActivityDate") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("LastActivityDate",  "{0:dd/MM/yyyy}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="IsApproved" HeaderText="Is Approved" />
                    </Columns>
        <RowStyle BackColor="#EFF3FB" />
        <EmptyDataTemplate>
            No users found.
        </EmptyDataTemplate>
        <EditRowStyle BackColor="#2461BF" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    <br />
    <br />
    <asp:Button ID="btn_Delete" runat="server" CssClass="SubmitBtn" Font-Bold="True"
        OnClick="btn_Delete_Click" Style="position: static" Text="Delete Selected" BackColor="White" BorderColor="#507CD1"
                            BorderStyle="Solid" BorderWidth="1px" Font-Names="Times New Roman"
                            Font-Size="10.5pt" ForeColor="#284E98"/><br />
    <br />
    <asp:Label ID="lblMsg" runat="server" Font-Bold="True" ForeColor="#FF0000" Style="position: static"  Width="211px"></asp:Label>

and In code behind :-


    private MembershipUserCollection allRegisteredUsers = Membership.GetAllUsers();
    MembershipUserCollection myuser = Membership.GetAllUsers();

    public void RefreshGridview()
    {
        gvUsers.DataSource = Membership.GetAllUsers();
        gvUsers.DataBind();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        btn_Delete.Visible = false;

        if (!IsPostBack)
        {
            //RefreshGridview();
            lblOnlineUsers.Text = Membership.GetNumberOfUsersOnline().ToString();
            lblTotalUsers.Text = allRegisteredUsers.Count.ToString();
            string[] alph = “A;B;C;D;E;F;G;J;K;L;M;N;O;P;Q;R;S;T;U;V;W;X;Y;Z;All”.Split(‘;’);
            //– Bind Reprater control to Alphapitical
            rptAlphabetBar.DataSource = alph;
            rptAlphabetBar.DataBind();
        }
    }

    //– for Reprater control
    protected void rptAlphabetBar_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        btn_Delete.Visible = true;

        gvUsers.Attributes.Add(“SearchByEmail”, false.ToString());
        if (e.CommandArgument.ToString().Length == 1)
        {
            gvUsers.Attributes.Add(“SearchText”, e.CommandArgument.ToString() + “%”);
            this.BindAllUsers(false);
        }
        else
        {
            gvUsers.Attributes.Add(“SearchText”, “”);
            this.BindAllUsers(false);
        }
    }

    private void BindAllUsers(bool reloadAllUsers)
    {
        MembershipUserCollection allUsers = null;
        if (reloadAllUsers)
            allUsers = Membership.GetAllUsers();

        string searchText = “”;
        if (!string.IsNullOrEmpty(gvUsers.Attributes["SearchText"]))
            searchText = gvUsers.Attributes["SearchText"];
        bool searchByEmail = false;
        if (!string.IsNullOrEmpty(gvUsers.Attributes["SearchByEmail"]))
            searchByEmail = bool.Parse(gvUsers.Attributes["SearchByEmail"]);
        if (searchText.Length > 0)
        {
            if (searchByEmail)
                allUsers = Membership.FindUsersByEmail(searchText);
            else
                allUsers = Membership.FindUsersByName(searchText);
        }
        else
        {
            allUsers = allRegisteredUsers;
        }
        gvUsers.DataSource = allUsers;
        gvUsers.DataBind();
    }

    //– Search button
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        btn_Delete.Visible = true;
        bool searchByEmail = (ddlUserSearchTypes.SelectedValue == “E-mail”);
        //gvUsers.Attributes.Add(“SearchText”, “%” + txtSearchText.Text + “%”);
        gvUsers.Attributes.Add(“SearchText”,  txtSearchText.Text + “%”);
        gvUsers.Attributes.Add(“SearchByEmail”, searchByEmail.ToString());
        BindAllUsers(false);
    }

    //– Delete button
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (GridViewRow row in gvUsers.Rows)
            {
                CheckBox checkbox = (CheckBox)row.FindControl(“cbxId”);
                if (checkbox.Checked == true)
                {
                    Label lblUserName = (Label)gvUsers.Rows[row.RowIndex].FindControl(“lblUserName”);
                    bool x = Membership.DeleteUser(lblUserName.Text);
                    if (x == true)
                    {
                        lblMsg.Text = “Selected deleted”;
                        RefreshGridview();
                        btn_Delete.Visible = false;
                    }
                    else
                    {
                        lblMsg.Text = “Try again”;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message.ToString();
        }
    }

    //– for Checkbox
    protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.Header))
        {
            //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
            ((CheckBox)e.Row.FindControl(“cbxAll”)).Attributes.Add(“onclick”, “javascript:SelectAll(‘” + ((CheckBox)e.Row.FindControl(“cbxAll”)).ClientID + “‘)”);

        }
    }
    protected void gvUsers_DataBound(object sender, EventArgs e)
    {
        if (gvUsers.Rows.Count == 0)
        {
          
            btn_Delete.Visible = false;
        }
        else
        {
            btn_Delete.Visible = true;
        }
    }

2) We will also create another Page called “UpdateUser.aspx” which we will update some data of spacific user from First Page through QueryString so our page will be like :-

<strong><span style="color: #0066ff">Update User Account:-</span></strong><br />
    </span>
    <br />
    <table id="table1" runat="server" border="1" bordercolor="blue" style="width: 322px;
        position: static" visible="true">
        <tr>
            <td style="width: 203px">
                <strong>User Name:</strong></td>
            <td>
                <asp:Label ID="UsernameLabel" runat="server" Font-Bold="True"></asp:Label></td>
        </tr>
        <tr>
            <td style="width: 203px">
                <strong>Email:</strong></td>
            <td>
                <asp:TextBox ID="EmailText" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td style="width: 203px">
                <strong>Password :</strong></td>
            <td>
                <asp:Label ID="lblPassword" runat="server" Font-Bold="True" Style="position: static"></asp:Label></td>
        </tr>
        <tr>
            <td style="width: 203px">
                <strong>Comment:</strong></td>
            <td>
                <asp:TextBox ID="CommentTextBox" runat="server" TextMode="multiline"></asp:TextBox></td>
        </tr>
        <tr>
            <td style="width: 203px">
                <asp:CheckBox ID="IsApprovedCheck" runat="server" Font-Bold="True" Text="Is Approved"
                    Width="105px" />
            </td>
            <td>
                <asp:CheckBox ID="IsLockedOutCheck" runat="Server" Font-Bold="True" Text="Locked Out" />
                <br />
            </td>
        </tr>
        <tr>
            <td colspan="2" style="height: 28px; text-align: center">
                <asp:Button ID="btn_Update" runat="server" CssClass="SubmitBtn" Font-Bold="True"
                    OnClick="Button1_Click" Text="Update" Width="106px" /></td>
        </tr>
    </table>

and in code behind :-


   MembershipUserCollection myuser = Membership.GetAllUsers();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Id"] != null)
        {
            if (!IsPostBack)
            {
                string userName = Request.QueryString["Id"].ToString();
                MembershipUser Current = myuser[userName];
                UsernameLabel.Text = Current.UserName;
                EmailText.Text = Current.Email;
                CommentTextBox.Text = Current.Comment;
                IsApprovedCheck.Checked = Current.IsApproved;
                IsLockedOutCheck.Checked = Current.IsLockedOut;
                lblPassword.Text = Current.GetPassword();
            }
        }

    }

    //– Update button
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string userName = Request.QueryString["Id"].ToString();
            MembershipUser Current = myuser[userName];
            Current.Email = EmailText.Text;
            Current.Comment = CommentTextBox.Text;
            Current.IsApproved = IsApprovedCheck.Checked;
            Membership.UpdateUser(Current);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            Response.Redirect(“~/Admin/ManageUsers.aspx”);
        }
    }

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net
  1. December 1, 2009 at 9:10 am

    Very Good Site

  2. yasserzaid
    December 1, 2009 at 4:31 pm

    Thank you jaganath for your comment hope my blog helps you and others
    With my best regards

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: