How to get logedin user details after valid login using form authentication in ASP.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

 

DATABASE:
USE [authentications]
GO

/****** Object:  Table [dbo].[formreg]    Script Date: 12/13/2016 13:16:13 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[formreg](
	[studentid] [int] IDENTITY(1,1) NOT NULL,
	[studentname] [varchar](50) NULL,
	[address] [varchar](50) NULL,
	[mobileno] [varchar](50) NULL,
	[email] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


SP LOGIN:
USE [authentications]
GO
/****** Object:  StoredProcedure [dbo].[login1]    Script Date: 12/13/2016 12:50:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[login1] 
(
@studentname varchar(50) =  null,
@email nvarchar(50)=  null
)
AS
Begin 
Select studentname from  formreg where studentname =@studentname and email =@email
End

 

LOGIN>ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Logins.aspx.cs" Inherits="FormsAuth.Logins" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <table align ="center">
    <tr>
    <td>
    <b>USERNAME</b></td>
    <td>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    <b>PASSWORD</b></td>
    <td>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    </td>
    <td>
        <asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" /></td></tr>
    </table>
    </div>
    </form>
</body>
</html>

LOGIN.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;

namespace FormsAuth
{
    public partial class Logins : System.Web.UI.Page
    {
        
        SqlCommand cmd;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string conn = ConfigurationManager.ConnectionStrings["muthu"].ToString();
                SqlConnection con = new SqlConnection(conn);
                //SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["muthu"].ConnectionString);
            }

        }

        bool ValidateUser(string user, string pass)
        {


            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["muthu"].ConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand("login1", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@studentname", user);
            cmd.Parameters.AddWithValue("@email", pass);
            return cmd.ExecuteScalar() is string;
           
        }



        protected void Login_Click(object sender, EventArgs e)
        {
            if (ValidateUser(TextBox1.Text, TextBox2.Text))
            {

                //Label1.Text = ("Welcome " + TextBox1.Text);
                FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
                //Response.Redirect("griddetails.aspx");

            }
            else
            {
                Label1.Text = "Invalid login!";
            }

        }

       
    }
}
GRIDDETAILS.ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="griddetails.aspx.cs" Inherits="FormsAuth.griddetails" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <tr>
             <td colspan="2">
                 <asp:validationsummary showmessagebox="true" showsummary="false" forecolor="Red" runat="server" id="validationSummary">
             </asp:validationsummary></td>
         </tr>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="False" 
            AllowPaging="True" AllowSorting="True" ShowFooter ="True"
         DataKeyNames ="studentid" OnPageIndexChanging ="pageindexchange" 
            OnRowCancelingEdit ="cancelledit" OnRowDeleting ="rowdeleting" OnRowCommand ="rowcommand"
          OnRowEditing ="rowediting" OnRowUpdating ="rowupdating" BackColor="White" 
            BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" 
            GridLines="Horizontal" >
            
            <AlternatingRowStyle BackColor="#F7F7F7" />
            
            <Columns>
            <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" Text="EDIT" CommandName="EDIT" ToolTip ="EDIT" />
                <asp:Button ID="Button2" runat="server" Text="DELETE" CommandName="DELETE" ToolTip ="DELETE" />
            </ItemTemplate>
            <EditItemTemplate>
            <asp:Button ID="Button3" runat="server" Text="UPDATE" CommandName="UPDATE" ToolTip ="UPDATE" />
             <asp:Button ID="Button4" runat="server" Text="CANCEL" CommandName="CANCEL" ToolTip ="CANCEL" />
            </EditItemTemplate>
            <FooterTemplate>
             <asp:Button ID="Button5" runat="server" Text="ADD" CommandName="NEWRECORD" ToolTip ="ADD"  Display ="None" />
            </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText ="STUDENTNAME" HeaderStyle-HorizontalAlign ="Center">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%#Eval("STUDENTNAME") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text ='<%#Eval ("STUDENTNAME") %>'></asp:TextBox>
           </EditItemTemplate>
           <FooterTemplate>
            <asp:TextBox ID="insertname" runat="server" ></asp:TextBox>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="please enter name" Text ="*" ControlToValidate ="insertname"  Display ="None" ></asp:RequiredFieldValidator>
           </FooterTemplate>      

<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
           </asp:TemplateField>
          <asp:TemplateField HeaderText = "ADDRESS" HeaderStyle-HorizontalAlign ="Center">
           <ItemTemplate>
            <asp:Label ID="Label2" runat="server" Text='<%#Eval("ADDRESS") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:TextBox ID="TextBox2" runat="server" Text = '<%#Eval("ADDRESS") %>'></asp:TextBox>
           </EditItemTemplate>
           <FooterTemplate>
               <asp:TextBox ID="insertaddress" runat="server"></asp:TextBox>
               <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="please enter address" ControlToValidate ="insertaddress" Text ="*"  Display ="None"></asp:RequiredFieldValidator>
           </FooterTemplate>              

<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
           </asp:TemplateField> 
           <asp:TemplateField HeaderText = "MOBILENO" HeaderStyle-HorizontalAlign ="Center">
           <ItemTemplate>
            <asp:Label ID="Label3" runat="server" Text='<%#Eval("MOBILENO") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:TextBox ID="TextBox3" runat="server" Text = '<%#Eval("MOBILENO") %>'></asp:TextBox>
           </EditItemTemplate>
           <FooterTemplate>
               <asp:TextBox ID="insertnumber" runat="server"></asp:TextBox>
               <asp:RequiredFieldValidator ID="RequiredFieldValidato3" runat="server" ErrorMessage="Please enter mobile no" ControlToValidate ="insertnumber" Text ="*"  Display ="None"></asp:RequiredFieldValidator>
               <asp:RegularExpressionValidator ID="rfvMobil1" ControlToValidate="insertnumber" ValidationExpression="^[7-9][0-9](\s){0,1}(\-){0,1}(\s){0,1}[0-9]{1}[0-9]{7}$"
             runat="server" ErrorMessage="Please enter Valid MobileNo"  Display ="None"></asp:RegularExpressionValidator>
                 </FooterTemplate>              

<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
           </asp:TemplateField>
           
           <asp:TemplateField HeaderText = "EMAIL" HeaderStyle-HorizontalAlign ="Center">
           <ItemTemplate>
            <asp:Label ID="Label4" runat="server" Text='<%#Eval("EMAIL") %>'></asp:Label>
           </ItemTemplate>
           <EditItemTemplate>
               <asp:TextBox ID="TextBox4" runat="server" Text = '<%#Eval("EMAIL") %>'></asp:TextBox>
           </EditItemTemplate>
           <FooterTemplate>
               <asp:TextBox ID="insertemail" runat="server"></asp:TextBox>
               <asp:RequiredFieldValidator ID="RequiredFieldValidato4" runat="server" ErrorMessage="insert valid emailid" ControlToValidate ="insertemail" Text ="*"  Display ="None"></asp:RequiredFieldValidator>
               <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="insertemail"  ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
                  </asp:RegularExpressionValidator>
                 </FooterTemplate>              

<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
           </asp:TemplateField>  

            
      
           
           
                 
            </Columns>
            <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
            <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
            <SortedAscendingCellStyle BackColor="#F4F4FD" />
            <SortedAscendingHeaderStyle BackColor="#5A4C9D" />
            <SortedDescendingCellStyle BackColor="#D8D8F0" />
            <SortedDescendingHeaderStyle BackColor="#3E3277" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

GRIDDETAILS>CS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace FormsAuth
{
    public partial class griddetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                bind();
            }
        }
        protected void bind()
    {
        string conn = ConfigurationManager.ConnectionStrings["muthu"].ToString();
        SqlConnection con = new SqlConnection(conn);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from formreg", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds, "formreg");
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }

    }


        protected void cancelledit (object sender , GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex =-1;
            bind();
        }
        protected void rowediting (object sender , GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            bind();
        }
        protected void pageindexchange(object sender, GridViewPageEventArgs e)
        {
            GridView1.EditIndex = e.NewPageIndex;
            bind();
        }

        protected void rowupdating(object sender, GridViewUpdateEventArgs e)
        {
            int studentid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["studentid"].ToString());
            TextBox TextBox1 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");
            TextBox TextBox2 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2");
            TextBox TextBox3 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3");
            TextBox TextBox4 = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4");
            string conn = ConfigurationManager.ConnectionStrings["muthu"].ToString();
            SqlConnection con = new SqlConnection(conn);
            con.Open ();
            SqlCommand  cmd = new SqlCommand ("update formreg set studentname ='"+TextBox1.Text +"', address ='"+TextBox2.Text +"', mobileno ='"+TextBox3.Text +"', email ='"+TextBox4.Text+"' where studentid ="+studentid ,con);
            cmd.ExecuteNonQuery ();
            con.Close();
            GridView1.EditIndex = -1;
            bind();

        }
        protected void rowdeleting(object sender, GridViewDeleteEventArgs e)
        {
            int studentid = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["studentid"].ToString());
            string conn = ConfigurationManager.ConnectionStrings["muthu"].ToString();
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            SqlCommand cmd = new SqlCommand(" delete from formreg where studentid =" + studentid, con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
            if (result == 1)
            {
                bind();
            }
        }

        protected void rowcommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName .Equals("NEWRECORD"))
            {

                TextBox insertname = (TextBox)GridView1.FooterRow.FindControl("insertname");
                TextBox insertaddress = (TextBox)GridView1.FooterRow.FindControl("insertaddress");
                TextBox insertnumber = (TextBox)GridView1.FooterRow.FindControl("insertnumber");
                TextBox insertemail = (TextBox)GridView1.FooterRow.FindControl("insertemail");
                string conn = ConfigurationManager.ConnectionStrings["muthu"].ToString();
                SqlConnection con = new SqlConnection(conn);
                con.Open();
                SqlCommand cmd = new SqlCommand(" insert into formreg values ('" + insertname.Text + "','" + insertaddress.Text + "','" + insertnumber.Text + "','" + insertemail.Text + "')", con);
                int result = cmd.ExecuteNonQuery();
                con.Close();
                if (result == 1)
                {
                    bind();
                }
            }

            

        }
    }
}

 

WEB>CONFIG:
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
	<connectionStrings>
		<add name="muthu" connectionString="Data Source=SRIRAM;Initial Catalog=authentications;Integrated Security=True" providerName="System.Data.SqlClient"/>
	</connectionStrings>
  <location path="Help.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
	<system.web>
		<authentication mode="Forms">
			<forms name="FRM" defaultUrl="griddetails.aspx" loginUrl="Logins.aspx" timeout="30">
			</forms>
		</authentication>
		<authorization>
			<deny users="?"/>
			<allow users="*"/>
		</authorization>
		<compilation debug="true" targetFramework="4.0"/>
		<membership>
			<providers>
				<clear/>
				<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
			</providers>
		</membership>
		<profile>
			<providers>
				<clear/>
				<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
			</providers>
		</profile>
		<roleManager enabled="false">
			<providers>
				<clear/>
				<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
				<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
			</providers>
		</roleManager>
	</system.web>
	<system.webServer>
		<modules runAllManagedModulesForAllRequests="true"/>
	</system.webServer>
</configuration>

 

You are viewing reply posted by: dharmendr 2 months ago.
Posted 2 months ago

Hi smuthu,

After successfully login save the user name in session and in the destination page filter the record based on that user.

"select * from formreg WHERE studentname = '"+ Session["userName"].ToString() +"'"

 

I agree, here is the link: http://e-iceblue.com/free-api