Unlock user from Code behind in ASP.NET

Asp.net Membership provide rich interface to implement security in your web application. There are many things you can do and even better if it doesn't fit your design then you can always extend it.

One such feature is locking user after certain number of failed attempt to login. This is great feature so today we will look at how we can provide a page from where admin can unlock the user who has been locked.


Here we have a user who is locked and on button click we will unlock all the locked users.

To get started, add a GridView on the page with view state mode disabled and button to call unlock code:

<form id="form1" runat="server">


<asp:GridView ID="GridView1" runat="server" ViewStateMode="Disabled">



<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Unlock All" />



After this let's open the code behind and on page_load event:

  1. Create a data table to hold records from membership
  2. Add data columns of type user and locked status
  3. Loop through all the users present in membership and add data row for each user
  4. Assign data table as data source for GridView
  5. Bind GridView


protected void Page_Load(object sender, EventArgs e)



DataTable dt = new DataTable();

DataColumn dcUN = new DataColumn("User", System.Type.GetType("System.String"));

DataColumn dcIsLocked = new DataColumn("Locked?", System.Type.GetType("System.Boolean"));





foreach (MembershipUser user in Membership.GetAllUsers())



DataRow row = dt.NewRow();

row[0] = user.UserName;

row[1] = user.IsLockedOut;





GridView1.DataSource = dt;





Now double click on button from page design view in order to create an event handler method for button click and call "UnockUser ()" method for all users.

Note: you can always pass username and just unlock that user; for the sake of demo I have unlocked all users since only one user is present in my demo table.


protected void Button1_Click(object sender, EventArgs e)


foreach (MembershipUser usr in Membership.GetAllUsers())


if (usr.IsLockedOut)






Tags: ,

ASP.NET | Membership