I am creating a basic role manager system where users of my website can be added to specific roles so that they can access exclusive parts of the website.
I have managed to add roles to my database but when I try to assign users to a particular role I get the 'Object reference not set to an instance of an object.' error and I can't work out why.
Here is my code:
protected void btnAssignRole_Click(object sender, EventArgs e)
{
try
{
if (!Roles.IsUserInRole(lstRoles.SelectedItem.Value))
{
Roles.AddUserToRole(lstUsers.SelectedItem.Value, lstRoles.SelectedItem.Value);
lstRoles.DataBind();
lstUsers.DataBind();
litRoleResult.Text = "User added to Role";
}
else
{
litRoleResult.Text = "User already in this Role";
}
}
catch (Exception ex)
{
litRoleResult.Text = ex.Message;
}
}
HTML:
<h1>Admin Page Test</h1>
<a href="ProductsAdmin.aspx">Products Admin</a>
<div id="UserAdmin">
<asp:TextBox ID="txtRoleName" runat="server"></asp:TextBox>
<asp:Button ID="btnAddRole" runat="server" Text="Create Role" OnClick="btnAddRole_Click" />
<div>
<asp:Label ID="Label1" runat="server" Text="Available Roles"></asp:Label>
<asp:ListBox ID="lstRoles" runat="server" DataSourceID="Roles_DS" DataTextField="RoleName" DataValueField="RoleName"></asp:ListBox>
<asp:SqlDataSource ID="Roles_DS" runat="server" ConnectionString="<%$ ConnectionStrings:db_1318766_zaraConnectionString %>" SelectCommand="SELECT [RoleName] FROM [vw_aspnet_Roles]"></asp:SqlDataSource>
<asp:Literal ID="litRole" runat="server"></asp:Literal>
</div>
<div>
<asp:Label ID="Label2" runat="server" Text="Available Users"></asp:Label>
<asp:ListBox ID="lstUsers" runat="server" DataSourceID="Users_DS" DataTextField="UserName" DataValueField="UserName">
</asp:ListBox>
<asp:SqlDataSource ID="Users_DS" runat="server" ConnectionString="<%$ ConnectionStrings:db_1318766_zaraConnectionString %>" SelectCommand="SELECT [UserName] FROM [vw_aspnet_Users]"></asp:SqlDataSource>
</div>
<div>
<asp:Button ID="btnAssignRole" runat="server" Text="Assign Role to User" OnClick="btnAssignRole_Click" />
</div>
<div>
<asp:Button ID="Button3" runat="server" Text="Remove User from Role" />
</div>
<div>
<asp:Button ID="Button4" runat="server" Text="Delete Role(s)" />
</div>
<asp:Literal ID="litRoleResult" runat="server"></asp:Literal>
</div>
Help appreciated.