For some reason, when you use the CreateUserWizard control in Visual Studio 2008, there is no built in method of adding the new user to existing roles that you have set up. You have to customize the wizard to do this for you. To achieve this customization, do the following:-
Firstly, in the create user step add listbox control to hold the existing roles. Next, in the page load event handler, fill the listbox with the roles you have already created, and for good measure, select the first role for the user, like so:-
protected void Page_Load(object sender,
EventArgs e)
{
//GS - Fill the listbox with the
//available roles
ListBox AvailableRoles =
CreateUserWizard1.CreateUserStep.
ContentTemplateContainer.
FindControl("RolesListbox")
as ListBox;
AvailableRoles.DataSource =
Roles.GetAllRoles();
AvailableRoles.DataBind();
//GS - Select first item in list
if (AvailableRoles.Items.Count > 0)
{
AvailableRoles.Items[0].Selected = true;
}
}
Then, in the created user event handler, add the new user to the selected roles, like so:-
protected void CreateUserWizard1_CreatedUser(
object sender, EventArgs e)
{
//GS - Add the newly created user to the
//selected roles
ListBox AvailableRoles =
CreateUserWizard1.CreateUserStep.
ContentTemplateContainer.
FindControl("RolesListbox")
as ListBox;
for (int i = 0; i <
AvailableRoles.Items.Count; i++)
{
if (AvailableRoles.Items[i].Selected)
{
Roles.AddUserToRole(
CreateUserWizard1.UserName,
AvailableRoles.Items[i].Value);
}
}
}
There is another way to do it (isn't there always?) You can also create a custom step in the CreateUserWizard to selected the Roles for the User and you can specify the Activate and Deactivate event handlers for this step, like so:-
<asp:WizardStep runat="server"
Title="Select User's Role"
OnActivate="ActivateStep"
OnDeactivate="DeactivateStep">
Select the Role(s) for this User<br />
<asp:ListBox ID="AvailableRoles"
runat="server"></asp:ListBox>
</asp:WizardStep>
This means that the code the you write in the event handlers is slightly simplified compared to that above.
protected void ActivateStep(object sender,
EventArgs e)
{
AvailableRoles.DataSource =
Roles.GetAllRoles();
AvailableRoles.DataBind();
if (AvailableRoles.Items.Count > 0)
{
AvailableRoles.Items[0].
Selected = true;
}
}
protected void DeactivateStep(object sender,
EventArgs e)
{
if (AvailableRoles.SelectedIndex >= 0)
{
Roles.AddUserToRole(
CreateUserWizard1.UserName,
AvailableRoles.SelectedValue);
}
}