How To Change User's Email In ASP.NET Membership?
It is very simple to change email or password of user if you use ASP.NET Membership provider. You can use code like this:
[ C# ]
using System;
// You have to include System.Web.Security namespace to use Membership class
using System.Web.Security;
public partial class ChangeEmailPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// First, get instance of certain user
MembershipUser mu = Membership.GetUser("YourUserName");
// Change password. You can change password only if enablePasswordRetrieval="true" in web.config
mu.ChangePassword("oldPassword", "newPassword");
// Change email address
mu.Email = "new@email.com";
// Save changes
Membership.UpdateUser(mu);
}
}
[ VB.NET ]
' You have to include System.Web.Security namespace to use Membership class
Imports System.Web.Security
Partial Class ChangeEmailPageVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' First, get instance of certain user
Dim mu As MembershipUser = Membership.GetUser("YourUserName")
' Change password. You can change password only if enablePasswordRetrieval="true" in web.config
mu.ChangePassword("oldPassword", "newPassword")
' Change email address
mu.Email = "new@email.com"
' Save changes
Membership.UpdateUser(mu)
End Sub
End Class
Note that, if you set requiresUniqueEmail="true" for Membership provider in web.config, the new email address must be unique. Otherwise, code will return an exception. You can use try-catch block to inform user that email address is already taken and to choose other address.
Related articles:
1. How to Show User Name of Currently Logged User?
2. How to Logout User in ASP.NET Membership?