Hi RichardSa,
Please refer below sample.
Note: For this sample i have used below article. For more details refer below artilce link.
HTML
Master
<div>
<asp:LoginView ID="LoginView" runat="server">
<LoggedInTemplate>
<div align="right">
Welcome
<asp:LoginName ID="LoginName1" runat="server" Font-Bold="true" />
<br />
<br />
<asp:Label ID="lblLastLoginDate" runat="server" />
<asp:LoginStatus ID="LoginStatus1" runat="server" />
</div>
</LoggedInTemplate>
</asp:LoginView>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
Home
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"
CodeBehind="Home.aspx.cs" Inherits="User_Login_CS.Home" EnableEventValidation="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h1>Home</h1>
<asp:Panel ID="pnlAssignRoles" runat="server" Visible="false">
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField DataField="Username" HeaderText="Username" />
<asp:TemplateField HeaderText="Role">
<ItemTemplate>
<asp:DropDownList ID="ddlRoles" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnUpdate" Text="Update" runat="server" CommandArgument='<%# Eval("UserId") %>'
OnClick="UpdateRole" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<hr />
<table>
<tr>
<td><b><asp:Label runat="server">RoleId:</asp:Label></b></td>
<td><asp:TextBox ID="txtRoleId" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><b><asp:Label runat="server">RoleName:</asp:Label></b></td>
<td><asp:TextBox ID="txtRoleName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Button ID="btnInsert" Text="Insert" runat="server" OnClick="OnInsert" /></td>
</tr>
</table>
</asp:Panel>
</asp:Content>
Login
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="User_Login_CS.Login" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Login ID="Login1" runat="server" OnAuthenticate="ValidateUser">
</asp:Login>
<hr />
Username: Admin<br />
Password: 12345<br />
Role: Administrator<br />
<br /><br />
Username: Mudassar<br />
Password: 12345<br />
Role: User
</asp:Content>
Namespaces
Home
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Login
using System.Data;
using System.Web.Security;
using System.Data.SqlClient;
using System.Configuration;
Code
Home
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (!this.Page.User.Identity.IsAuthenticated)
{
Response.Redirect("~/Login.aspx");
}
if (this.Page.User.IsInRole("Administrator"))
{
pnlAssignRoles.Visible = true;
gvUsers.DataSource = GetData("SELECT UserId, Username, RoleId FROM Users");
gvUsers.DataBind();
}
}
}
private DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlRoles = (e.Row.FindControl("ddlRoles") as DropDownList);
ddlRoles.DataSource = GetData("SELECT RoleId, RoleName FROM Roles");
ddlRoles.DataTextField = "RoleName";
ddlRoles.DataValueField = "RoleId";
ddlRoles.DataBind();
string assignedRole = (e.Row.DataItem as DataRowView)["RoleId"].ToString();
ddlRoles.Items.FindByValue(assignedRole).Selected = true;
}
}
protected void UpdateRole(object sender, EventArgs e)
{
GridViewRow row = ((sender as Button).NamingContainer as GridViewRow);
int userId = int.Parse((sender as Button).CommandArgument);
int roleId = int.Parse((row.FindControl("ddlRoles") as DropDownList).SelectedItem.Value);
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Users SET RoleId = @RoleId WHERE UserId = @UserId"))
{
cmd.Parameters.AddWithValue("@UserId", userId);
cmd.Parameters.AddWithValue("@RoleId", roleId);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
protected void OnInsert(object sender, EventArgs e)
{
int roleId = int.Parse(txtRoleId.Text);
string roleName = txtRoleName.Text;
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Roles(RoleId,RoleName) VALUES (@RoleId,@RoleName)", con))
{
cmd.Parameters.AddWithValue("@RoleId", roleId);
cmd.Parameters.AddWithValue("@RoleName", roleName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Login
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx");
}
}
}
protected void ValidateUser(object sender, EventArgs e)
{
int userId = 0;
string roles = string.Empty;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Validate_User"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Username", Login1.UserName);
cmd.Parameters.AddWithValue("@Password", Login1.Password);
cmd.Connection = con;
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
userId = Convert.ToInt32(reader["UserId"]);
roles = reader["Roles"].ToString();
con.Close();
}
switch (userId)
{
case -1:
Login1.FailureText = "Username and/or password is incorrect.";
break;
case -2:
Login1.FailureText = "Account has not been activated.";
break;
default:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Login1.UserName, DateTime.Now, DateTime.Now.AddMinutes(2880), Login1.RememberMeSet, roles, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (ticket.IsPersistent)
{
cookie.Expires = ticket.Expiration;
}
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet));
break;
}
}
}
Screenshot
Output
RoleId |
RoleName |
1 |
Administrator |
2 |
User |
3 |
HR |
4 |
Manager |