Storing User Profile into a Custom Table using CreateUser Wizard control

I discussed how you can add extra controls to CreateUserWizard(CUW) Control in the blog post HERE.

Assuming you have gone through the post above, what we will do here is store this extra information collected in CUW into a custom database.

Other option is storing in asp.net Profiles. Check References section at the end to see how to store user information in profiles.

Add Extra Fields to CUW Control:

Lets say we want to collect FirstName and LastName of the User while creating a user.With the help of previous post add two textboxes namely FirstName and LastName. Add Validation controls accordinly.

Create a Custom Table to store User Profile(here FirstName and LastName)

  • Add a new Table to your Membership Database. Here I have named it User_Profile.
  • Add 3 columns namely UserId - type uniqueidentifier, FirstName - type varchar(50) and LastName - type varchar(50)
  • Set UserId as Primary Key
  • Create a Foreign key relationship between UserId of User_Profile table and aspnet_Users table. You can look sample example screenshots here.

So once you have your table ready to store the information lets go ahead and look at the code how to insert values into it.

Inserting FirstName and LastName into User_Profile

We will use the CreatedUser event of CUW control to do this job. In the design Mode, double click the Create User button. In the code behind for CreateUser page you will see an event handler added for CreatedUser event. Here is the code that says the rest:

C#:

protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)

{

// Get the UserId of the just-added user

MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);

Guid newUserId = (Guid)newUser.ProviderUserKey;

//Get Profile Data Entered by user in CUW control

String FirstName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName")).Text;

String LastName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName")).Text;

// Insert a new record into User_Profile

// Get your Connection String from the web.config. MembershipConnectionString is the name I have in my web.config

string connectionString = ConfigurationManager.ConnectionStrings["MembershipConnectionString"].ConnectionString;

string insertSql = "INSERT INTO User_Profile(UserId,FirstName, LastName) VALUES(@UserId, @FirstName, @LastName)";

using (SqlConnection myConnection = new SqlConnection(connectionString))

{

myConnection.Open();

SqlCommand myCommand = new SqlCommand(insertSql, myConnection);

myCommand.Parameters.AddWithValue("@UserId", newUserId);

myCommand.Parameters.AddWithValue("@FirstName", FirstName);

myCommand.Parameters.AddWithValue("@LastName", LastName);

myCommand.ExecuteNonQuery();

myConnection.Close();

}

}

VB.NET:

Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles CreateUserWizard1.CreatedUser
        ' Get the UserId of the just-added user
        Dim newUser As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)
        Dim newUserId As Guid = DirectCast(newUser.ProviderUserKey, Guid)

        'Get Profile Data Entered by user in CUW control

        Dim FirstName As String = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("FirstName"), TextBox).Text
        Dim LastName As String = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("LastName"), TextBox).Text

        ' Insert a new record into User_Profile

        ' Get your Connection String from the web.config. MembershipConnectionString is the name I have in my web.config
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("MembershipConnectionString").ConnectionString

        Dim insertSql As String = "INSERT INTO User_Profile(UserId,FirstName, LastName) VALUES(@UserId, @FirstName, @LastName)"
        Using myConnection As New SqlConnection(connectionString)
            myConnection.Open()
            Dim myCommand As New SqlCommand(insertSql, myConnection)
            myCommand.Parameters.AddWithValue("@UserId", newUserId)
            myCommand.Parameters.AddWithValue("@FirstName", FirstName)
            myCommand.Parameters.AddWithValue("@LastName", LastName)

            myCommand.ExecuteNonQuery()
            myConnection.Close()
        End Using
    End Sub

-------------------------

Most of the code is self-explanatory. We get the UserId of the newly created user and the values in FirstName and LastName textboxes.

Then its simple sql database insertion code.

NOTE: Make sure you have -->  oncreateduser="CreateUserWizard1_CreatedUser"  set in your CUW Markup (aspx). If is it not set this custom CreatedUser event handler will not be executed. So the user will be created in your DB but the profile data will not be updated as the code above is not executed at all. Check HERE what I mean.

Concerns:

  • We haven't taken into consideration one scenario. What if something goes wrong between UserCreation and storing profile. i.e. User is created successfully but Profile does not get stored. May be we will discuss that in some other article.
  • You can add exception handling.

Thanks for reading.

References:

Having issues implementing above?

If you are facing any issues I would suggest you post your question here - http://forums.asp.net/25.aspx - with more details.Then post the link to that thread below in the comment. I will take a look at it as soon as I get a chance. Your chances to get prompt response increases by posting on that forum.

66 Comments

  • Excellent! Exactly what I am looking for!

  • Hi

    If I inserted a checkbox, how do I access the state of the checkbox in the wizard?

  • hi

    I did exactly as the above, the user is created in the system aspnetdb tables but no entries are made in the user_profile table

    Can you help?

    athompson@cits.uwi.tt

  • I think the wrong event handler is being used - the code does not execute - I think this code should be in the Created User event handler.

  • andrethompson
    Are you getting any error?
    The code is already placed in CreatedUser event handler.

  • I am new to programming. I have copied and pasted this code and it is giving error and it does not recognise commands like SqlConnection and SqlCommand. Any idea why?

  • Hasan,

    You should include referenc to System.Data.SqlClient namespace like:

    using System.Data.SqlClient;

  • This does not work. No one have not found a way yet.

  • Sevensnake77,
    If you can tell what is not working we can try making it work.

  • " CreateUserWizard1: CreateUserWizardStep.ContentTemplate does not contain an IEditableTextControl with ID UserName for the username. "
    This is what am facing whil running ..any solution??

  • Sabari M.D
    That is because for some reason UserName TextBox is either removed or Renamed in your CreateUserWizard. Go to the SourceView of that page and you need to add a TB with ID UserName.
    If you have any question please share your CUW markup code here.

  • My control always come back null any suggestions  
    Dim usertxt As TextBox = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox)
           'Dim Email As TextBox = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("UserName"), TextBox)
           Dim user As MembershipUser = Membership.GetUser(usertxt.Text)
           Dim userId As Guid = DirectCast(user.ProviderUserKey, Guid)
           ' Dim RoleId As Guid = DirectCast(RoleGroup, Guid)
           Dim RoleIDValue As DropDownList = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("DropDownList1"), DropDownList)
           'Dim RoleId As New Guid(RoleIDValue.SelectedValue)
           Dim txtfname As TextBox = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtfname"), TextBox)
           Dim txtlname As TextBox = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtlname"), TextBox)
           Dim MiddleNameTextBox As TextBox = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Company"), TextBox)

  • you mean something like this.

  • ok I started debuging, I see the text i entered in the box. But it does not insert into the database. and no errors.

    "address11"

    TemplateSourceDirectory "/" String
    Text "address here" String
    TextMode SingleLine {0} System.Web.UI.WebControls.TextBoxMode
    ToolTip "" String

  • I got it. And I did not have to use next button, everything in one.

    Dim fname As TextBox = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtfname"), TextBox)

    cmdInsert.Parameters.Add(New SqlParameter("@fname", Data.SqlDbType.VarChar, 500))

    cmdInsert.Parameters("@fname").Value = fname.Text

  • This is exactly what I'm looking for too. But I'm using VB. Can you please help me out by converting the codes to VB. I'll be very grateful for that. Thanks!

    Vishal

  • NYFP,
    Sorry for getting back too late...but still
    Check this C# to VB.NET Converter:
    http://www.developerfusion.com/tools/convert/csharp-to-vb/

  • This code doesn't work for me. It is not been executed.

    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
    MembershipUser newUser = Membership.GetUser(CreateUserWizard1.UserName);

    Guid newUserId = (Guid)newUser.ProviderUserKey;
    //Get Profile Data Entered by user in CUW control

    String FirstName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtFName")).Text;
    String LastName = ((TextBox)CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtLName")).Text;


    Then i put Response.Write("Executed?"); and a break point. It doesn't show nor break at that point.
    Mind telling me why?
    It would be best that u can email to me at nkm.kevin@live.com
    Thank you...

  • Currently our website uses forms authentication with a custom profile for each user. Right now, each user is associated with one company. However, I want to update our website so that one user could access 4 different companies while another user could access 3 different ones. Roles will not work for my situation. I was hoping to still use the membership and profile classes that I have. What I really want to do is each user has a user record in the user table (for membership), but they could have multiple rows in the profile table...and then load the correct profile into the Context.Profile when they change what company they are associated with. Is there any clean way to do this with asp.net forms that I'm not seeing?

  • Re: to lookingforanswers

    I'm actually doing the same exact thing and what I did was create the custom table as described above added a column for the companies, due to my admins can be in charge of 4 companies at a time, I added 4 company columns. and on the create user wizard I added a checkbox if more then one company should be added to the user being created. I got it working perfectly

  • how to extract the value of the default createUSerWizard fields????? please helppppppppppppppppppppppp

  • abdo,

    If your CUW ID is CreateUserWizard1 then you can get the username by:
    CreateUserWizard1.UserName.

    You can also find the UserName Textbox control as mentioned in the article similar to finding FirstName,LastName TBxs.

  • In membership table it stores data but in User_Profile nothing

  • Virat,
    are you getting any errors? did you set breakpoints and see if your code is executed?
    I doubt your code is executed.
    Can you post your code and probelm here: http://forums.asp.net/25.aspx
    Then post your thread's link here and I will look into it.

  • Thank You for a nice peice of article. I was looking for this for a great deal of time.

  • Thanks a lot! This was exactly what I was looking for :)

  • Can we use update query instead of insert query directly in CreateUserWizard1_CreatedUser function?

  • Ashwini,
    yes..you can do whatever coding you need in CreateUser handler. Now when you say update query I assume you have data in your table to update...and a mapping UserId which actually is a bit complex so it may or may not be doable....
    I need some more information on what you are trying to achieve.

  • Thanks great stuff. this is what am looking for.

    PLEASE can you write another tutorial on how to enable user edit profile information?

    THANKS

  • Why is it that i do not have the type membership user? I have the aspnetdb and i use the user_ID as foreign key in one of my tables. I am trying to insert the user_ID when user is created from the CUW. I added extra fields but i can't get the user_ID from the aspnet_user table?

  • I have placed a few textboxes in the CUW for some input to another table however when i go to the button click action and try to insert the text to the table the text boxes do not appear to be accessible?

  • XayBlu,
    1: You will need reference to System.Web.Security namespace to get MembershipUser.
    2: You will have to do FindControl as shown in the code. To get better idea of your issue, can you post your question here - http://forums.asp.net/25.aspx - with more details and post the link to that thread here. I will take a look at it.

  • I've done the instructions and codes given above, there are no build errors, but when i clicked the "create user" button, an error "Object reference not set to an instance of an object" occurred.

    What do you think is the problem?

  • @Aldrin Butcon:
    Which line is throwing exception?

  • Sorry for the late reply..

    The problem is in this line:

    myCommand.ExecuteNonQuery()

    I think the problem is in my ConnetionString, but I tried to add a SqlDataSource to my page then renamed MembershipConnectionString to ConnectionString. Well, it worked for me, but is it necessary to have a SqlDataSource.? Thanks in advance...

  • Aldrin,
    Not it is not necessary to have SQL Datasource on the page. The code assumes you have a connectionstring name "MembershipConnectionString" in your web.config. So it seems it wasn't able to find one and since you changed the name to "ConnectionString" which I believe was added to your web.config when you added sqlDataSource.
    So you don't need a sqldatasource but you surely need a valid connectionstring in your web.config.

  • Now I understand, thanks there genius...

  • firby,
    Are you getting any errors? Did you place breakpoints and see if you save code is executed?

    Can you post your question here - http://forums.asp.net/25.aspx - with more details and post the link to that thread here. I will take a look at it.

  • hi
    the code works but why am i getting 2 same records inserted?
    any idea?

  • jiun,

    Looks like your CreatedUser event is fired twice. If you are using vb.net and have hooked up your event in your .aspx code then remove "Handles CreateUserWizard1.CreatedUser" from the code-behind. Can your share your CUW markup?

  • On This line "Dim newUser As Membership = Membership.GetUser(CreateUserWizard1.UserName)
    I received the following:
    Value of type System.Web.Security.MembershipUser cannot be converted to System.Web.Security.Membership
    email address: gvt99@bellsouth.net
    I apreciate any help
    Thank you

  • @Gus,
    My bad, the code-converter did something wrong. Check I updated that code line. It should be:

    Dim newUser As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)

    Thanks for pointing out.

  • Works. Thank you

  • Storing user profile into a custom table using createuser wizard control.. Ho-o-o-o-t :)

  • Storing user profile into a custom table using createuser wizard control.. Smashing :)

  • Thanks dear it is working for me

  • Hardik,
    Sorry for late reply. The only reason I can think of is it is not able to find/access your Sql Server. May be you want to check your connection string is correctly pointing to right server/database and the account has proper rights.

  • This is a nice article.

    "What if something goes wrong between UserCreation and storing profile" To address this should the below works

    try

    {
    ----- Whatever the above code here.
    }

    catch (Exception RegisterException)
    {
    Trace.Write(RegisterException.ToString());
    Membership.DeleteUser(((TextBox)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("UserName")).Text);
    }

  • Thanks Kangla for the inputs. Good point.

  • I'm new to programming, I cant see any connection string in my web.config file can I add it and if so how?

  • chieftain,
    Sorry for late reply. If you are using default membership provider, the default connection string -"LocalSqlServer" is taken from machine.config. You can override this by adding new connection to your web.config and adjusting the membership provider connectionStringName property.

  • Its a fantastic post (almost the one I was looking for). I want to store the information into my own table [tblUserInfo] in my own Database [dbProject] and do not want to add data into the aspnet_Users table but use the Membership functionalities to store profile info. Any lead? Thanks in advance.

  • really nice explanation bro.... good job!

  • This is a great tutorial, thanks. One tip, add:
    ON DELETE CASCADE
    ...at the end of your CONSTRAINT in your User_Profile table. This will allow user deletes from the primary table to cascade to this table also.

  • Hi,

    This is a great tutorial! Thanks.

    How can I add a check to see if if the aspnet_Users table values have been inserted, before the fields for my other table get inserted.
    Im finding that foreign key is trying to insert before the aspnet_Users table is updated. Causing a foreign key constraint.

  • @hozdaman,

    CreatedUser event is fired only after user is created. And the code is retrieving the ProviderUserKey. So not sure if you are using some different event or something else would be an issue.

  • Hi,

    I posted the question on forums.asp.net/.../1.

    Can you help ?

    Thank you.

  • Hello Guys,

    Everything was fine except the below error that I am getting once I click the "Create User" button. Please also note that the data entered into original fields are correctly inserted into the database but it does not gets inserted from the additional fields that I have created and it throws the below error:

    Server Error in '/' Application.

    Keyword not supported: 'metadata'.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentException: Keyword not supported: 'metadata'.

    Source Error:

    Line 41:

    Line 42:

    Line 43:         using (SqlConnection myConnection = new SqlConnection(connectionString))

    Line 44:

    Line 45:         {

    CAN SOMEONE PLEASE LET ME KNOW WHAT IS THE CAUSE FOR THESE?

    Regards,

    David

  • David,

    It should be something in your page code. Check for "metadata" and post the relevant code.

  • I am trying to add First and Last name of the user to the wizard. It inserts all the fields except for custom fields in the "aspnet_UserProfile" table which I created. I get this error for "myCommand.ExecuteNonQuery()" Invalid object name 'aspnet_UserProfile'. I am using vbs2012.

    I have pasted your code for the event. My insert SQL is correct as I did run the query for the table and it did insert.

    Thank you for all your documentation.
    ~ Nita

  • Nita,

    'aspnet_UserProfile' is your new table correct? And you are trying to save using inline query or stored procedure?

  • I am ttying to use the inline query; Yes aspnet_UserProfile is my new table. This is what I have:

    Protected Sub CreateUserWizard1_CreatedUser(sender As Object, e As EventArgs) Handles CreateUserWizard1.CreatedUser
    ' Get the UserId of the just-added user
    Dim newUser As MembershipUser = Membership.GetUser(CreateUserWizard1.UserName)
    Dim newUserId As Guid = DirectCast(newUser.ProviderUserKey, Guid)

    'Get Profile Data Entered by user in CUW control

    Dim FirstName As String = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtFName"), TextBox).Text
    Dim LastName As String = DirectCast(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("txtLName"), TextBox).Text

    ' Insert a new record into User_Profile

    ' Get your Connection String from the web.config.
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("IDBConnectionString").ConnectionString

    Dim insertSql As String = "INSERT INTO aspnet_UserProfile(UserId, FirstName, LastName) VALUES(@UserId, @FirstName, @LastName)"
    Using myConnection As New Data.SqlClient.SqlConnection(connectionString)
    myConnection.Open()
    Dim myCommand As New Data.SqlClient.SqlCommand(insertSql, myConnection)
    myCommand.Parameters.AddWithValue("@UserId", newUserId)
    myCommand.Parameters.AddWithValue("@FirstName", FirstName)
    myCommand.Parameters.AddWithValue("@LastName", LastName)

    myCommand.ExecuteNonQuery()
    myConnection.Close()
    End Using
    End Sub

  • Nita,
    Is your new table in the same database as your membership tables or different?
    To what is the database your IDBConnectionString pointing at?
    As per the error aspnet_UserProfile is not found.

  • IDB is the database for the system. ASPNETDB.MDF is the aspnet membership database. They are two different database, ok so I need the connection string for ndf file right?

  • Yes, you will need the connectionstring to where your aspnet_UserProfile table is.

  • Thanks Mr.Guru. I am going to transfer the database to the server and there I will merge them together. Currently I am working on my desktop.
    ~ Nita

Comments have been disabled for this content.