Insert (Save) Session ID in Database using C# and VB.Net in ASP.Net

Last Reply 4 months ago By pandeyism

Posted 4 months ago

How to insert session ID of user into table using asp.net c#

 please guide

if (Session["EmpID"] == null)
{
    Response.Redirect("LogingForm.aspx");
}

 

You are viewing reply posted by: pandeyism 4 months ago.
Posted 4 months ago

Hi akhter,

Refer below sample.

HTML

CS.aspx

Id : <asp:TextBox ID="txtId" runat="server"></asp:TextBox><br />
<asp:Button Text="Insert" runat="server" OnClick="Save" />

Default.aspx

<asp:GridView ID="gvSessioDetails" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="SessionId" HeaderText="SessionId" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data.SqlClient;
using System.Configuration;
using System.Data;

VB.Net

Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data

Code

CS.aspx.cs

protected void Save(object sender, EventArgs e)
{
    Session["Id"] = txtId.Text;
    Response.Redirect("Default.aspx");
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    int id = Convert.ToInt16(Session["Id"]);
    string sessionId = Session.SessionID;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("INSERT INTO tblSesioData VALUES(@Id,@SessionId)", con);
    cmd.Parameters.AddWithValue("@Id", id);
    cmd.Parameters.AddWithValue("@SessionId", sessionId);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    cmd = new SqlCommand("SELECT Id, SessionId FROM tblSesioData", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    gvSessioDetails.DataSource = dt;
    gvSessioDetails.DataBind();
}

VB.Net

VB.aspx.vb

Protected Sub Save(ByVal sender As Object, ByVal e As EventArgs)
    Session("Id") = txtId.Text
    Response.Redirect("Default.aspx")
End Sub

Default.aspx.vb

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Handle.Me.Load
    Dim id As Integer = Convert.ToInt16(Session("Id"))
    Dim sessionId As String = Session.SessionID
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("INSERT INTO tblSesioData VALUES(@Id,@SessionId)", con)
    cmd.Parameters.AddWithValue("@Id", id)
    cmd.Parameters.AddWithValue("@SessionId", sessionId)
    con.Open()
    cmd.ExecuteNonQuery()
    con.Close()
    cmd = New SqlCommand("SELECT Id, SessionId FROM tblSesioData", con)
    Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
    Dim dt As DataTable = New DataTable()
    da.Fill(dt)
    gvSessioDetails.DataSource = dt
    gvSessioDetails.DataBind()
End Sub

Screenshot